shell 編程空格注意事項

1.定義變量時, =號的兩邊不可以留空格.
eg:
gender=femal————right
gender =femal———–wrong
gender= femal———–wrong
2.條件測試語句 [ 符號的兩邊都要留空格.
eg:
if [ $gender = femal ]; then——-right.
echo “you are femal”;
fi

if[ $gender...-----------------------wrong
if [$gender...----------------------wrong.

3.條件測試的內容,如果是字符串比較的話, 比較符號兩邊要留空格!
eg:
if [ $gender = femal ]; then——-right.
if [ $gender= femal ]; then——–wrong.
if [ $gender=femal ]; then———wrong.

4.如果if 和 then寫在同一行, 那麼,注意, then的前面要跟上 ; 號.如果 then 換行寫, 那麼也沒問題.
eg:
if [ $gender = femal ]; then——-right.
if [ $gender = femal ]
then——————————-right.
if [ $gender = femal ] then——-wrong. then前面少了 ; 號.
提示出錯信息:
syntax error near unexpected token then
同理,還有很多出錯信息 比如
syntax error near unexpected token fi 等都是這樣引起的.

5.if 後面一定要跟上 then. 同理
elif 後面一定要跟上 then.
不然提示出錯信息:
syntax error near unexpected token else

1)if 語句後面需要跟着then,同時前面要有分號;
2) 空格非常重要,shell 會認爲空格前的爲一個命令,如果a=3 認爲是賦值操作,如果寫成a = 3,那麼就會認爲a爲一個命令 this=`ls -l |grep ‘^-' | wc -l `
3) 操作符之間要用空格分開 ,如 test ! -d $1,其中的!和-d就要用空格分開
空格是命令解析中的重要分隔符

6. 命令和其後的參數或對象之間一定要有空格

if [ -x"~/Workspace/shell/a.sh" ];then


只有 -x 後有空格才表示緊跟其後的字符串是否指向一個可執行的文件名,否則就成了測試 -x"~/Workspace/shell/a.sh" 這個字符串是不是空。

7.取變量值的符號'$'和後邊的變量或括號不能有空格

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章