Reload Environment Variables in a Bash Script
How can I reload the environment variables in a Bash Script. I am updating ~/.bashrc in the same script and want the changes to get reflected.
I have tried using
source 开发者_Python百科~/.bashrc
The following is my script
#!/bin/bash
echo $PATH
echo "export PATH=\$PATH:/home/user/test" >> ~/.bashrc
source ~/.bashrc
echo $PATH
Both the echos return the same value of $PATH. But when I run echo $PATH on another instance of bash it returns the newly added path.
Any help would be appreciated.
Thanks.
The following is the content of my .bashrc file (without the modifications from the script)
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
HISTCONTROL=ignoredups:ignorespace
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
shopt -s checkwinsize
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
case "$TERM" in
xterm-color) color_prompt=yes;;
esac
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
color_prompt=yes
else
color_prompt=
fi
fi
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
Your .bashrc starts:
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
Since your script does not have PS1 set (because it is not interactive), it doesn't reset path because it exits early - exactly as B Mitch suggested. To demonstrate, modify your script:
#!/bin/bash
echo $PATH
echo "export PATH=\$PATH:/home/user/test" >> ~/.bashrc
PS1='$ '
source ~/.bashrc
echo $PATH
精彩评论