shell script执行方式差异(source, sh script, ./script)

shell script执行方式差异(source, sh script, ./script):

1、利用直接执行(sh script, ./script)的方式來执行 script

      不论是绝对路径/相对路径还是${PATH} 內,或者利用 bash (或 sh) 來执行时,该script都会使用一个新的bash环境来执行脚本中的命令,即用这种方式时,其实script是在子程序的bash内执行,这样当子程序完成后,在子程序内的各项变量或动作将会结束而不会传回到父程序中。

[root@Test bin]$ echo ${firstname} ${lastname}
    <==确认这两个参数并不存在
[root@Test bin]$ sh showname.sh
Please input your first name: shu
Please input your last name:  yu 

Your full name is: shu yu      <==在 script 运行中,这2个参数生效
[root@Test bin]$ echo ${firstname} ${lastname}
    <==这两个参数在父程序的 bash 中还是不存在
2、使用source执行脚本,在父程序中执行。

[root@Test bin]$ source showname.sh
Please input your first name: shu
Please input your last name:  yu

Your full name is: shu yu
[root@Test bin]$ echo ${firstname} ${lastname}
shu yu 
这样在父程序中就已生效,因为source对script的执行方式是 showname.sh 在父程序中执行,因此各项动作都会在原本的bash内生效,这也是不登出系统而要让某些写入~/.bashrc 的设定生效时,需要使用 source ~/.bashrc 而不能使用bash  ~/.bashrc 。



猜你喜欢

转载自blog.csdn.net/heart_1014/article/details/54311212