如何在Bash脚本中重新加载环境变量。我正在同一个脚本中更新〜/ .bashrc,并希望更改得到反映。
我尝试过使用
source ~/.bashrc
以下是我的剧本
#!/bin/bash
echo $PATH
echo "export PATH=\$PATH:/home/user/test" >> ~/.bashrc
source ~/.bashrc
echo $PATH
两个回声都返回$ PATH的相同值。但是当我在另一个bash实例上运行echo $ PATH时,它会返回新添加的路径。
任何帮助都将不胜感激。
感谢。
以下是我的.bashrc文件的内容(没有脚本的修改)
# ~/.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
答案 0 :(得分:4)
你的.bashrc开始了:
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
由于您的脚本没有设置PS1(因为它不是交互式的),因此它不会重置路径,因为它会提前退出 - 正如B Mitch建议的那样。要演示,请修改脚本:
#!/bin/bash
echo $PATH
echo "export PATH=\$PATH:/home/user/test" >> ~/.bashrc
PS1='$ '
source ~/.bashrc
echo $PATH