Difference between source and ./ execution of linux scripts

ε祈祈猫儿з 提交于 2019-12-31 03:17:06

问题


csh:

set a=0 
echo "a is $a"

when i do ./my_script.csh output is:

a is 

when i do source my_script.csh output is:

a is 0 

Why is it so . As i know that ./ execution uses new shell.


回答1:


check if variable "a" is set in your current shell:

set | grep '^a='

Remember that once you source script to your current shell, all it's global variables are there until unset or you exit the current shell. You may want to start a new shell, source the script, end exit shell to perform valid tests.

I don't know the context of your problem, but you may want to export some key variables to have their copies in every subprocess.




回答2:


That's right, ./my_script.csh starts a new shell, and uses the #! that you should have at the top of the file to select which shell to run (which should be csh in this case).

source my_script.csh runs the script in the current shell.

If the script is incorrectly run in, for example, the bash shell, set a=0 is not the syntax for setting an environment variable in bash, so the code won't work as you expected, because you're using the wrong shell.

Take a look at the #! at the top of the file. Is it correct?



来源:https://stackoverflow.com/questions/5645854/difference-between-source-and-execution-of-linux-scripts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!