1. 程式人生 > >#!/bin/sh與#!/bin/bash的區別

#!/bin/sh與#!/bin/bash的區別

shell學習 clas 基礎 not text 類型 css roo 快的

Linux 中的 shell 有很多類型,其中最常用的幾種是: Bourne shell (sh)、C shell (csh) 和 Korn shell (ksh), 各有優缺點。Bourne shell 是 UNIX 最初使用的 shell,並且在每種 UNIX 上都可以使用, 在 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 指向它,以獲得更快的腳本執行速度。Dash Shell 比 Bash Shell 小的多,符合POSIX標準。 Ubuntu繼承了Debian,所以從Ubuntu 6.10開始默認是Dash Shell。
  1. luotaijia@ubuntu:~$ ls -l /bin/sh /bin/bash
  2. -rwxr-xr-x 1 root root 801808 2010-08-11 03:58 /bin/bash
  3. lrwxrwxrwx 1 root root 4 2012-11-28 08:06 /bin/sh -> dash
應該說, /bin/sh 與 /bin/bash 雖然大體上沒什麽區別, 但仍存在不同的標準. 標記為 “#!/bin/sh” 的腳本不應使用任何 POSIX 沒有規定的特性 (如 let 等命令, 但 “#!/bin/bash” 可以). Debian 曾經采用 /bin/bash 更改 /bin/dash,目的使用更少的磁盤空間、提供較少的功能、獲取更快的速度。但是後來經過 shell 腳本測試存在運行問題。因為原先在 bash shell 下可以運行的 shell script (shell 腳本),在 /bin/sh 下還是會出現一些意想不到的問題,不是100%的兼用。

點擊(此處)折疊或打開

  1. 1 a=12345
  2. 2
  3. 3 let "a += 1"
  4. 4 echo "a = $a"
  5. 5
  6. 6 b=${a/23/BB}
  7. 7 echo "b = $b"

點擊(此處)折疊或打開

  1. luotaijia@ubuntu:~/文檔/shell學習練習$ /bin/sh 3.2..1.sh
  2. 3.2..1.sh: 3: let: not found
  3. a = 12345
  4. 3.2..1.sh: 6: Bad substitution
  5. luotaijia@ubuntu:~/文檔/shell學習練習$ /bin/bash 3.2..1.sh
  6. a = 12346
  7. b = 1BB46
  8. luotaijia@ubuntu:~/文檔/shell學習練習$
   註: b=${a/23/BB} 把變量a中的23(僅限第一次出現)替換成BB, 並賦值給 b.

#!/bin/sh與#!/bin/bash的區別