我刚接触bash shell脚本编程,面临一个挑战。我知道只需要执行以下操作就可以重新加载我的“.profile”文件:
. .profile
但是我正在尝试在我写的bash脚本中执行相同的操作,但它就是不起作用。 有什么想法吗? 我可以提供什么其他信息来澄清问题吗?
谢谢
尝试使用以下命令重新加载当前的shell:
source ~/.profile
source
命令会将文件作为脚本运行...在最坏的情况下,如果有人在他们的bash_profile中使用变量赋值,例如MyVar="$foo$MyVar"
,那么source ~/.profile
将给出最终结果MyVar="$foo$MyVar$MyVar"
,因此$MyVar
之后的值将是错误的。(不管好坏实践,只是询问其他解决方案) - Jeffrey Mvutu Mabilama当尝试重新加载/源化~/.profile文件时,会出现一些问题。
[这是指Ubuntu linux-在某些情况下,命令的细节可能会有所不同]
答案1)
在终端直接运行意味着不会创建子shell。因此,您可以使用以下两个命令之一:
source ~/.bash_profile
或者
. ~/.bash_profile
在这两种情况下,这将使用.profile文件的内容更新环境。
第2点)您可以通过调用任何bash脚本来启动它。
sh myscript.sh
或者
. myscript.sh
.myscript.sh
命令。
为了确保您的脚本不在子shell中运行,您可以使用此函数。(以下示例适用于Ubuntu shell)
#/bin/bash
preventSubshell(){
if [[ $_ != $0 ]]
then
echo "Script is being sourced"
else
echo "Script is a subshell - please run the script by invoking . script.sh command";
exit 1;
fi
}
我希望这能消除一些常见的误解! :D 祝好运!
试一试:
cd
source .bash_profile
这个 bash 脚本在一个独立的子 shell 中运行。为了让它正常工作,你需要同时引用另外一个脚本。
.profile
文件:. $HOME/.profile
,并且你需要通过引用它来启动你的脚本。就像这样:. /path/to/yourscript
。 - Dennis Williamson尝试:
#!/bin/bash
# .... some previous code ...
# help set exec | less
set -- 1 2 3 4 5 # fake command line arguments
exec bash --login -c '
echo $0
echo $@
echo my script continues here
' arg0 "$@"
source .bash_profile
还是. ./.bash_profile
都会返回"bash: .: 是一个目录"的错误提示。 - Heinz