一、常見shell類型
1. Bourne shell (sh)
UNIX 最初使用,且在每種 UNIX 上都可以使用。在 shell 編程方面相當優秀,但在處理與用戶的交互方面做得不如其他幾種shell。
2. C shell (csh)
csh, the C shell, is a command interpreter with a syntax similar to the C programming language.一個語法上接近於C語言的shell。
3. Korn shell (ksh)
完全向上兼容 Bourne shell 並包含了 C shell 的很多特性。
4. Bourne Again shell (bash)
因為Linux 操作系統缺省的 shell。即 bash 是 Bourne shell 的擴展,與 Bourne shell 完全向后兼容。在 Bourne shell 的基礎上增加、增強了很多特性。可以提供如命令補全、命令編輯和命令歷史表等功能。包含了很多 C shell 和 Korn shell 中的優點,有靈活和強大的編程接口,同時又有很友好的用戶界面。
5. Debian Almquist Shell(dash)
原來bash是GNU/Linux 操作系統中的 /bin/sh 的符號連接,但由於bash過於復雜,有人把 bash 從 NetBSD 移植到 Linux 並更名為 dash,且/bin/sh符號連接到dash。Dash Shell 比 Bash Shell 小的多(ubuntu16.04上,bash大概1M,dash只有150K),符合POSIX標准。Ubuntu 6.10開始默認是Dash。
二、規范和建議
標記為 “#!/bin/sh” 的腳本不應使用任何 POSIX 沒有規定的特性 (如 let 等命令, 但 “#!/bin/bash” 可以)。bash支持的寫法比dash(ubuntu中的sh)多很多。想要支持 sh xx.sh 運行的,必須遵照 POSIX 規范去寫。想要腳本寫法多樣化,不需要考慮效率的,可以將文件頭定義為 #!/bin/bash , 而且不要使用 sh xx.sh 這種運行方式
三、bash和dash區別
語法上的主要的區別有:
1. 定義函數
bash: function在bash中為關鍵字
dash: dash中沒有function這個關鍵字
2. select var in list; do command; done
bash:支持
dash:不支持, 替代方法:采用while+read+case來實現
3. echo {0..10}
bash:支持{n..m}展開
dash:不支持,替代方法, 采用seq外部命令
4. here string
bash:支持here string
dash:不支持, 替代方法:可采用here documents
5. >&word重定向標准輸出和標准錯誤
bash: 當word為非數字時,>&word變成重定向標准錯誤和標准輸出到文件word
dash: >&word, word不支持非數字, 替代方法: >word 2>&1; 常見用法 >/dev/null 2>&1
6. 數組
bash: 支持數組, bash4支持關聯數組
dash: 不支持數組,替代方法, 采用變量名+序號來實現類似的效果
7. 子字符串擴展
bash: 支持parameter:offset:length,parameter:offset:length,{parameter:offset}
dash: 不支持, 替代方法:采用expr或cut外部命令代替
8. 大小寫轉換
bash: 支持parameterpattern,parameterpattern,{parameter^^pattern},parameter,pattern,parameter,pattern,{parameter,,pattern}
dash: 不支持,替代方法:采用tr/sed/awk等外部命令轉換
9. 進程替換<(command), >(command)
bash: 支持進程替換
dash: 不支持, 替代方法, 通過臨時文件中轉
10. [ string1 = string2 ] 和 [ string1 == string2 ]
bash: 支持兩者
dash: 只支持=
11. [[ 加強版test
bash: 支持[[ ]], 可實現正則匹配等強大功能
dash: 不支持[[ ]], 替代方法,采用外部命令
12. for (( expr1 ; expr2 ; expr3 )) ; do list ; done
bash: 支持C語言格式的for循環
dash: 不支持該格式的for, 替代方法,用while+((expression))實現13.let命令和((expression))bash:有內置命令let,也支持((expression))方式dash:不支持,替代方法,采用((expression))實現13.let命令和((expression))bash:有內置命令let,也支持((expression))方式dash:不支持,替代方法,采用((expression))或者外部命令做計算
14. $((expression))
bash: 支持id++,id–,++id,–id這樣到表達式
dash: 不支持++,–, 替代方法:id+=1,id-=1, id=id+1,id=id-1
15. 其它常用命令
bash: 支持 echo -e, 支持 declare
dash: 不支持。