浅谈ubuntu履行.sh文件几种方式区分
前言
区别的script履行方式会造成不一样的结果,特别对bash的环境影响很大,脚本的履行方式有大概以下几种方式。
首先写一个简单的test.sh文件:
#!/bin/bash read -p "Please input your first name:" firstname read -p "Please input your last name:" lastname echo -e "\nYour full name is: $firstname $lastname"
使用sh test.sh履行
使用 sh test.sh 来履行script文件,该方法标明使用 sh 这类shell来履行test.sh文件,sh已是一种被bash替换的shell,虽然我们在test.sh中声明使用 #!/bin/bash 来履行我们的文件,但此时使用sh而不是bash,则#!/bin/bash 已不起作用。
使用bash test.sh 履行
该方法其实与 sh test.sh 的原理一样,只是使用了 /bin/bash 该种shell来履行我们的脚本文件。
所以,其实使用 dash test.sh’ 也是可以的,只是取决于自己想使用那种shell来履行脚本,但sh、bash、dash三者有些许差别,对部份关键字如 let,bash支持,而sh和dash其实不支持,对部份关键字则选择使用bash。
使用点 . 履行
该种方式使用之前一定要为文件添加履行的权限:
$ chmod +x test.sh
添加完履行权限以后,即可以使用 ./test.sh 来履行脚本,该方式与 bash test.sh 是一样的 ,默许使用 bin/bash 来履行我们的脚本。
只有该种履行方式需要对文件添加履行权限,其他方式其实不需要。
使用source履行
使用source则也能够直接履行我们的脚本:
source test.sh
区分
当我们使用 sh test.sh 、bash test.sh 、 ./test.sh 履行脚本的时候,该test.sh运行脚本都会使用一个新的shell环境来履行脚本内的命令,也就是说,使用这3种方式时,其实script是在子进程的shell内履行,当子进程完成后,子进程内的各项变量和操作将会结束而不会传回到父进程中。
没法理解??看下面例子:
[root@ubuntu] # bash test.sh Please input your first name: yao <==输入firstname Please input your last name: pentonBin <==输入lastname Your full name is: yao pentonBin [root@ubuntu] # echo $firstname <==这里没有输出
如果使用source方法来履行脚本呢?
[root@ubuntu] # source test.sh Please input your first name: yao <==输入firstname Please input your last name: pentonBin <==输入lastname Your full name is: yao pentonBin [root@ubuntu] # echo $firstname yao <==这里输出firstname
也就是说,source方法履行脚本是在父进程中履行的,test.sh的各项操作都会在本来的shell内生效,这也是为何不注销系统而要让某些写入~/.bashrc的设置生效时,需要使用 source ~/.bashrc 而不能使用 bash ~/.bashrc
本篇文章到此结束,如果您有相关技术方面疑问可以联系我们技术人员远程解决,感谢大家支持本站!
文章来源:丸子建站
文章标题:浅谈ubuntu履行.sh文件几种方式区分
https://www.wanzijz.com/view/66629.html