Linux中的shell有多種類型,其中最常用的幾種是Bourne shell(sh)、C shell(csh)和Korn shell(ksh)。三種shell各有優缺點。
Bourne shell是UNIX最初使用的shell,並且在每種UNIX上都可以使用。Bourne shell在shell編程方面相當優秀,但在處理與用戶的交互方面做得不如其他幾種shell。
Linux操作系統缺省的shell是Bourne Again shell,它是Bourne shell的擴展,簡稱Bash,與Bourne shell完全向后兼容,並且在Bourne shell的基礎上增加、增強了很多特性。Bash放在/bin/bash中,它有許多特色,可以提供如命令補全、命令編輯和命令歷史表等功能,它還包含了很多C shell和Korn shell中的優點,有靈活和強大的編程接口,同時又有很友好的用戶界面。
GNU/Linux 操作系統中的 /bin/sh 是 bash(Bourne-Again Shell)的符號鏈接,
但鑒於 bash 過於復雜,有人把 ash 從 NetBSD 移植到 Linux 並更名為 dash(Debian Almquist Shell),並建議將 /bin/sh 指向它,以獲得更快的腳本執行速度。Ubuntu 號稱自從他們在 6.10 版里這樣做了以后,系統啟動速度有了明顯的提升。Debian 計划在下一個發行版(代號 lenny)中也將 dash 作為默認的 /bin/sh。
/bin/sh與/bin/bash的細微區別
在shell腳本的開頭往往有一句話來定義使用哪種sh解釋器來解釋腳本。
目前研發送測的shell腳本中主要有以下兩種方式:
(1) #!/bin/sh
(2) #!/bin/bash
值得注意的是:
1. sh一般設成bash的軟鏈
[work@zjm-testing-app46 cy]$ ll /bin/sh
lrwxrwxrwx 1 root root 4 Nov 13 2017 /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 Nov 25 2017/bin/bash
lrwxrwxrwx 1 root root 4 Jan 29 00:39 /bin/sh -> bash
[root@localhost yuhj]#