先了解下bash中什么時候該用空格,什么時候不該用。
1. 等號賦值兩邊不能有空格
2. 命令與選項之間需要空格
3. 管道兩邊空格可有可無
我們來看看常見的問題
1. 賦值時等號兩邊或者只有左邊多了空格
igi@gentoo ~ $ var1 = testbash: var1: command not foundigi@gentoo ~ $ echo ${var1:?error}bash: var1: errorigi@gentoo ~ $ echo ${var1?error}bash: var1: errorigi@gentoo ~ $ var2 =testbash: var2: command not foundigi@gentoo ~ $ echo ${var2:?error}bash: var2: errorigi@gentoo ~ $ echo ${var2?error}bash: var2: error這里我用了bash的變量擴展,${var1:?error}當var1為unset或null(未定義或空)時, 報指定錯誤; ${var1?error}當var1為unset時,報指定錯誤 。從執行結果來看,如果等號左邊有空格,則變量名當成命令執行,結果報command not found,變量沒有被賦值
2. 賦值時等號左邊沒有空格,右邊有空格(這種情況有點特別,你會發現兩種情況)
igi@gentoo ~ $ var= testigi@gentoo ~ $ var= nocmdbash: nocmd: command not found
同樣是等號右邊有空格,第一條命令沒報錯,而第二條報錯了。
這是因為shell中有這么一種執行命令的方式: var=string command
命令command將得到變量var的值(至于在命令執行后,變量var的值是否保留下來,bash4中沒有保留,但我在dash中發現時保留下來的,不 同的shell對這個的處理不同), 由于test是個命令,而nocmd不是,所以報了command not found.
igi@gentoo ~ $ var=newtest eval echo /$varnewtestigi@gentoo ~ $ echo $var
注意: 這里我使用了eval, 是想避免在第一次解析時$var被替換成空字符串, 不然就會出現下面的情況(下面是錯誤的測試方法,在echo還沒執行時,$var已經被替換成空字符串)
代碼如下:
igi@gentoo ~ $ var=newtest echo $var
igi@gentoo ~ $ echo $var
到這里,相信大家都明白了吧, 對于等號賦值,左右兩邊不可以有空格,雖然右邊有空格不一定報錯,但那絕對不是你想要的結果。
3. 命令和選項之間必須有空格
這個似乎大家都明白,為何我還這么羅嗦呢?說到這里,不得不提一下一個非常特別的命令: [ 命令(你沒看錯,是[ ), 也就是test命令(當然bash中,這是個內置命令,但在這里不影響
我們的理解)。或許你會覺得[命令眼熟,沒錯,我保證你見過它,來看看下面的例子
igi@gentoo ~ $ if [ "abc" = "abc" ]; then echo ‘they are the same'; fithey are the sameigi@gentoo ~ $ type -a [[ is a shell builtin[ is /usr/bin/[
想起來了吧?[命令經常用到if判斷中,當然也有人喜歡這么寫
igi@gentoo ~ $ [ "abc" = "cba" ] || echo ‘they are not the same'they are not the sameigi@gentoo ~ $ type -a [[ is a shell builtin[ is /usr/bin/[
新聞熱點
疑難解答