/bin/sh與/bin/bash的細微區別
原文:不詳
在shell腳本的開頭往往有一句話來定義使用哪種sh解釋器來解釋腳本。
目前研發送測的shell腳本中主要有以下兩種方式:
(1) #!/bin/sh
(2) #!/bin/bash
在這里求教同福客棧的各位大俠們一個問題:
以上兩種方式有什么區別?對於腳本的實際運行會產生什么不同的影響嗎?
腳本test.sh內容:
#!/bin/sh
source pcy.sh #pcy.sh並不存在
echo hello
執行./test.sh,屏幕輸出為:
./test.sh: line 2: pcy.sh: No such file or directory
由此可見,在#!/bin/sh的情況下,source不成功,不會運行source后面的代碼。
修改test.sh腳本的第一行,變為#!/bin/bash,再次執行./test.sh,屏幕輸出為:
./test.sh: line 2: pcy.sh: No such file or directory
hello
由此可見,在#!/bin/bash的情況下,雖然source不成功,但是還是運行了source后面的echo語句。
但是緊接着我又試着運行了一下sh ./test.sh,這次屏幕輸出為:
./test.sh: line 2: pcy.sh: No such file or directory
表示雖然腳本中指定了#!/bin/bash,但是如果使用sh 方式運行,如果source不成功,也不會運行source后面的代碼。
為什么會有這樣的區別呢?
junru同學作了解釋
1. sh一般設成bash的軟鏈
[work@zjm-testing-app46 cy]$ ll /bin/sh
lrwxrwxrwx 1 root root 4 Nov 13 2006 /bin/sh -> bash
2. 在一般的linux系統當中(如redhat),使用sh調用執行腳本相當於打開了bash的POSIX標准模式
3. 也就是說 /bin/sh 相當於 /bin/bash --posix
所以,sh跟bash的區別,實際上就是bash有沒有開啟posix模式的區別
so,可以預想的是,如果第一行寫成 #!/bin/bash --posix,那么腳本執行效果跟#!/bin/sh是一樣的(遵循posix的特定規范,有可能就包括這樣的規范:“當某行代碼出錯時,不繼續往下解釋”)
例如:
[root@localhost yuhj]# head -n1 x.sh
#!/bin/sh
[root@localhost yuhj]# ./x.sh
./x.sh: line 8: syntax error near unexpected token `<'
./x.sh: line 8: ` while read line; do { echo $line;((Lines++)); } ; done < <(route -n)'
[root@localhost yuhj]#
[root@localhost yuhj]# head -n1 x.sh
#!/bin/bash
[root@localhost yuhj]#./x.sh
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.202.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
0.0.0.0 192.168.202.2 0.0.0.0 UG 0 0 0 eth0
Number of lines read = 4
[root@localhost yuhj]#
[root@localhost yuhj]# head -n1 x.sh
#!/bin/bash --posix
[root@localhost yuhj]#
[root@localhost yuhj]# ./x.sh
./x.sh: line 8: syntax error near unexpected token `<'
./x.sh: line 8: ` while read line; do { echo $line;((Lines++)); } ; done < <(route -n)'
[root@localhost yuhj]# whereis sh bash
sh: /bin/sh /usr/share/man/man1/sh.1.gz /usr/share/man/man1p/sh.1p.gz
bash: /bin/bash /usr/share/man/man1/bash.1.gz
[root@localhost yuhj]# ll /bin/sh /bin/bash
-rwxr-xr-x 1 root root 735004 May 25 2008 /bin/bash
lrwxrwxrwx 1 root root 4 Jan 29 00:39 /bin/sh -> bash
[root@localhost yuhj]#
轉載自:http://www.cppblog.com/erran/archive/2012/05/24/176038.aspx