天天看點

shell中空格的用法

1.定義變量時, =号的兩邊不可以留白格.

eg:

gender=femal————right

gender =femal———–wrong

gender= femal———–wrong

2.條件測試語句 [ 符号的兩邊都要留白格.

if [ $gender = femal ]; then——-right.

echo “you are femal”;

fi

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

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

3.條件測試的内容,如果是字元串比較的話, 比較符号兩邊要留白格!

if [ $gender= femal ]; then——–wrong.

if [ $gender=femal ]; then———wrong.

4.如果if 和 then寫在同一行, 那麼,注意, then的前面要跟上 ; 号.如果 then 換行寫, 那麼也沒問題.

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.取變量值的符号'$'和後邊的變量或括号不能有空格