shell 中的空格

2022-04-08 17:28:07 字數 2058 閱讀 5780

1. 變數賦值時 = 兩邊不能有空格.

2. if比較時 = 兩遍有空格.

3. [ 的左右兩邊和  ] 的左邊有空格,

1 #!/bin/sh

2# 字串比較

3 aa=

4 bb="

hello"5

cc="

world"6

7 # 1

.注意判斷中的字串變數用雙引號括起來(不括起來在某些情況下會出錯);

8 # 2

.字串判斷相等用乙個等號,不是兩個;

9 # 3.=兩邊有空格;

10 # 4

.[的左右兩邊,]的左邊有空格.

11if [ "

$" = "

$" ]; then

12echo

"yes"13

else

14echo"no

"15fi16

以下摘自

1.定義變數時, =號的兩邊不可以留空格.

eg:gender=femal————right

gender =femal———–wrong

gender= femal———–wrong

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

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

echo 「you are femal」;

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

shell 指令碼中 中空格的說明

shell指令碼對空格有嚴格的規定,賦值語句等號兩邊不能有空格,而字串比較,等號兩邊必須有空格 賦值時 i 1 i i 1 用作賦值時,兩邊絕對不能有空格比較時 if a b 用作比較判斷時,兩邊必須有空格除此以外的注意點就是 a b 後面要有空格,前面要有個 if if if commands t...

shell指令碼的空格

基本語法 shell的if語法和c語言等高階語言非常相似,唯一需要注意的地方就是shell的if語句對空格方面的要求比較嚴格 其實shell對所有語法的空格使用都比較嚴格 如果在需要空格的地方沒有打上空格,都會報錯。如if 1x ip x then echo abc fi中少乙個空格都會報錯。另外s...

shell指令碼 空格

eg gender femal right gender femal wrong gender femal wrong eg if gender femal then right.echo you are femal fiif gender.wrong if gender.wrong.eg if g...