[英]Changing the value of a export variable from a bash script
I did the following from a bash shell. 我从bash shell中进行了以下操作。
export myPath="/home/user/dir"
Then I verified the value of this by 'echo'ing this value from both shell and a inside a bash script. 然后,我通过从shell和bash脚本内部“回显”此值来验证此值。 Both worked fine. 两者都很好。
Then I tried setting the value of this variable from inside a script like this. 然后,我尝试从这样的脚本中设置此变量的值。 myPath="/home/user/newdir"
and tried printing this variable from shell. myPath="/home/user/newdir"
并尝试从shell打印此变量。 I thought the variable will hold the updated value, but it was showing the old value. 我以为该变量将保留更新后的值,但它显示的是旧值。
How can I update the value from a script? 如何从脚本更新值? I am looking to do it without using source
if possible. 我正在寻找尽可能不使用source
的方法。
To make the variables persist after the script finishes, you have to run it using the source
command: 要使变量在脚本完成后仍然存在,必须使用source
命令运行它:
When a script is run using
source
it runs within the existing shell, any variables created or modified by the script will remain available after the script completes. 当使用source
运行脚本时,它在现有的Shell中运行,脚本完成后,由脚本创建或修改的任何变量将保持可用。 In contrast if the script is run just as filename, then a separate subshell (with a completely separate set of variables) would be spawned to run the script. 相反,如果脚本仅以文件名的形式运行,则将生成单独的子shell(具有完全独立的变量集)来运行脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.