执行命令的方式
执行 Shell 脚本的方式通常有以下四种
方式一: bash ./test.sh
方式二:./test.sh
方式三: source ./test.sh
方式四:. ./test.sh
执行方式的区别
方式一 bash 方式执行脚本的话, 会在当前的终端下面产生一个 bash 子进程来运行脚本, 所以对当前的环境是没有影响的.
[[email protected] usr]# bash ./test.sh
方式二./test.sh 的方式运行, 则脚本第一行声明是哪个 Shell 解释器就会产生哪个 Shell 解释器的子进程来运行脚本, 如果声明的 Shell 解释器是 bash, 则与方式一类似.
[[email protected] usr]# ./test.sh
方式三和方式四执行的时候, 和上面的方式一和方式略有点不同.
因为他执行的时候是通过当前的终端来执行 Shell 脚本的, 不会产生子进程, 所以会当前的环境是有影响的.
- [[email protected] usr]# source ./test.sh
- [[email protected] usr]# . ./test.sh
执行方式的影响对比
上述也提及到了方式一和方式二, 由于是会产子进程来执行 Shell 脚本, 所以对当前的环境是没有影响的; 而方式二和方式三, 是在当前的终端执行 Shell 脚本, 所以是会对当前的环境是有影响的.
举个栗子, 编写一个切换目录的 test.sh 脚本, 内容如下
- #!/bin/bash
- # 切换到 tmp 目录
- cd /tmp
- # 打印当前目
- pwd
那么使用方式一执行 test.sh 脚本, 其结果如下:
- [[email protected] /]# bash test.sh
- /tmp
- [[email protected] /]# pwd
- /
可以发现, 使用方式一去执行脚本, 不需要给予执行权限.
方式二执行 test.sh 脚本, 其结果如下:
- [[email protected] /]# chmod u+x test.sh
- [[email protected] /]# ls -l test.sh
- -rwxr--r--. 1 root root 64 Sep 26 18:34 test.sh
- [[email protected] /]# ./test.sh
- /tmp
- [[email protected] /]# pwd
- /
方式一和方式二执行完切换到 / tmp 目录的 Shell 脚本后, 终端所在的目录没有变化, 还是在 / 根目录, 说明方式一和方式二的执行方式是对当前的环境是没有影响的.
原因就是方式一和二执行 Shell 脚本时, 会产生子进程来执行 Shell 脚本, 当脚本执行结束后, 子进程退出, 回到了父进程, 那么对当前所在的环境就不会产生影响.
接下来看, 方式三执行结果:
- [[email protected] /]# source ./test.sh
- /tmp
- [[email protected] tmp]# pwd
- /tmp
方式四执行结果:
- [[email protected] /]# . ./test.sh
- /tmp
- [[email protected] tmp]# pwd
- /tmp
从上面方式三和方式四的执行结果, 可以发现, 执行完切换到 / tmp 目录的 Shell 脚本后, 当前的终端环境所在的目录已经被切换了到了 / tmp 目录, 说明方式三和方式四的执行方式是对当前的环境是有影响的.
小结
方式一和方式二执行 Shell 脚本时, 会产生子进程来执行 Shell 脚本, 当脚本执行结束后, 子进程退出, 回到了父进程, 那么对当前所在的环境就不会产生影响.
而方式二和方式四是在当前环境执行 Shell 脚本, 也就是在当前进程执行 Shell 脚本, 其执行的结果就会影响当前的环境.
来源: http://www.bubuko.com/infodetail-3216297.html