此種問題只在 Ubuntu 下才會出現!安裝 debian 系統根本不存在此類問題,因為只有Ubuntu 把默認的 bash 替換成了 dash.

在學習 Shell 腳本的時候,有兩個例子在運行時出現異常。比如,我在 test-dash.sh腳本輸入如下內容:?
echo -e "Trekshot. \a \n"?
declare -i number=7?
echo $number?
在 Ubuntu 系統下使用 sh test-bash.sh 運行將出現如下提示信息:?
-e Trekshot.?
test-dash.sh: 2: declare: not found:?

有兩個問題:?
a. echo 的參數 '-e' 怎么也打印出來了??
b. 一個簡單的整數聲明語句為何提示 "declare: not found"??

1.出現此問題的原因并非代碼本身有誤,而是 Ubuntu 系統的問題。我們在編寫腳本時,第一行經常要寫這么一行內容:#!/bin/bash. 這是對該腳本所使用的 shell 進行聲明,因為Linux 上的 shell 并非只有一種,而各個 shell 的語法是由差別的。之所以把 echo 命令的參數誤打出來,就是因為 sh 命令沒有理解該語法,即當前使用的并不是 bash.下面來證明:?
獲取 /bin 中相關文件的屬性:?
-rwxr-xr-x 1 root root 725136 2008-05-13 02:48 bash?
-rwxr-xr-x 1 root root 87924 2008-06-21 00:07 dash?
lrwxrwxrwx 1 root root 4 2010-03-25 14:29 sh -> dash?

這表明在執行 sh test-dash.sh 的時候,我們使用的是一個叫 "dash" 的命令(注意 sh實為鏈接文件),而并不是腳本第一行中聲明的 bash. 這就是上面現象的原因。 其實,如果使用 bash test-dash.sh 命令執行的話,上面兩個錯誤根本不會出現。?

2.dash(Debian Almquist SHell) Ubuntu 自 6.10 后,將先前的 bashshell 更換成了dash (有待考證). 在設置 dash 的說明中有下面文字:?

The default /bin/sh shell on Debian and Debian-based systems is bash.?

However, since the default shell is required to be POSIX-compliant, any?
shell that conforms to POSIX, such as dash, can serve as /bin/sh. You may?
wish to do this because dash is faster and smaller than bash.?

大致意思是說默認的 shell 是 bash shell, 但只要是能兼容 POSIX 的 shell 都可以,而dash 比 bash 速度更快、更小巧,因此 Ubuntu 安裝了 dash.?

3.怎么能把 dash 去掉而使用默認的 bash?使用如下命令:?
sudo dpkg-reconfigure dash?
此命令是對已安裝的包進行重新配置,在菜單(dash-bash-sh.png)中選擇是否將 sh 鏈接到 dash (Install dash as /bin/sh?) 選擇否即可。?

附圖一:Ubuntu 下設置 dash 界面

ubuntu 設置 dash - 烈火網