在前一篇文章里面(怎樣入Bash編程的坑?),我們列出了的很多Bash的資料。這篇文章是其中一篇的整理而來,原文的地址為Bash -- Standard Shell
Bash Conditionals -- 條件語句
基本的選擇
最基礎(chǔ)的條件語句就是if
了:
if something ; then
do_stuff;
fi
以fi
收尾,這個千萬不要忘了。
多條分支的條件語句
這個很顯然了,使用else
和elif
來走不同的邏輯分支:
if something ; then
do_stuff
elif something_else ; then
do_other_stuff
elif full_moon ; then
howl
else
turn_into_a_newt
fi
注意,在條件語句下,每個區(qū)塊中必須要有至少一行語句,即下面的寫法是錯誤的:
if some_stuff ; then
# A statement is required here. a blank or a comment
# isn't enough!
else
einfo "Not some stuff"
fi
如果你實在是沒有語句可以放,可以用:
來表示空語句,類似python中的pass
:
if some_stuff ; then
# Do nothing
:
else
einfo "Not some stuff"
fi
條件檢驗
進行比對或者是文件的屬性檢驗時,相關(guān)的語句需要用[]
或者[[]]
框起來
# is $foo zero length?
if [[ -z "${foo}" ]] ; then
die "Please set foo"
fi
# is $foo equal to "moo"?
if [[ "${foo}" == "moo" ]] ; then
einfo "Hello Larry"
fi
# does "${ROOT}/etc/deleteme" exist?
if [[ -f "${ROOT}/etc/deleteme" ]] ; then
einfo "Please delete ${ROOT}/etc/readme manually!"
fi
注意一般
[[]]
要比[]
安全一些,盡量多使用前者吧
這是因為[[]]
是bash的一個語法結(jié)構(gòu),而[]
中框起來的語句其實是被視為內(nèi)聯(lián)的。看下面這個例子:
bash$ [ -n $foo ] && [ -z $foo ] && echo "huh?"
huh?
bash$ [[ -n $foo ]] && [[ -z $foo ]] && echo "huh?"
bash$
字符串比對
一般的字符串比對形式為string1 operator string2
,其中操作符可以為
Operator | Purpose |
---|---|
== 或者=
|
字符串相等 |
!= |
字符串不等 |
< |
按字典順序小于 |
> |
按字典順序大于 |
=~ |
正則匹配(Bash 3 Only) |
字符串檢驗
通常字符串檢驗的形式為-operator "string"
,其中操作符可以為
Operator | Purpose |
---|---|
-z |
字符串長度為0 |
-n |
字符串長度非0 |
注意:如果你確認(rèn)一個變量被設(shè)置了而且非空,使用`-n "${BLAH}",而非"-n $BLAH",后一種情況在變量未設(shè)置時會出錯。
整型數(shù)比較
通常整型數(shù)比較的形式為int1 -operator int2
,可選的操作符如下:
Operator | Purpose |
---|---|
-eq |
等于 |
-ne |
不等 |
-lt |
小于 |
-le |
小于或等于 |
-gt |
大于 |
-ge |
大于或等于 |
文件檢驗
文件檢驗的形式為-operator "filename"
,其中操作符為可以:
Operator | Purpose |
---|---|
-a file |
Exists (use -e instead) |
-b file |
Exists and is a block special file |
-c file |
Exists and is a character special file |
-d file |
Exists and is a directory |
-e file |
Exists |
-f file |
Exists and is a regular file |
-g file |
Exists and is set-group-id |
-h file |
Exists and is a symbolic link |
-k file |
Exists and its sticky bit is set |
-p file |
Exists and is a named pipe (FIFO) |
-r file |
Exists and is readable |
-s file |
Exists and has a size greater than zero |
-t fd |
Descriptor fd is open and refers to a terminal |
-u file |
Exists and its set-user-id bit is set |
-w file |
Exists and is writable |
-x file |
Exists and is executable |
-O file |
Exists and is owned by the effective user id |
-G file |
Exists and is owned by the effective group id |
-L file |
Exists and is a symbolic link |
-S file |
Exists and is a socket |
-N file |
Exists and has been modified since it was last read |
文件比較
文件比較的一般形式為"fille1" -operator "file2"
。其中 操作符如下:
Operator | Purpose |
---|---|
file1 -nt file2 |
文件1比文件2更新(根據(jù)修改日期比較),或者文件1存在而文件2不存在 |
file1 -ot file2 |
文件1比文件2更舊,或者文件1不存在而文件2存在 |
file1 -ef file2 |
file1 and file2 refer to the same device and inode numbers. |
布爾運算
||
或,&&
與,!
非。
注意:在
[[]]
內(nèi)部,[[ ! -f file ]] && bar
可以工作,而[[ -f foo && bar]]
則無法正常工作,這是因為[[]]
內(nèi)無法運行命令。
Bash中的遍歷結(jié)構(gòu)
和其他的編程語言類似,遍歷結(jié)構(gòu)分為兩種,for
關(guān)鍵詞和while
關(guān)鍵詞。
下面是一些例子的
for myvar in "the first" "the second" "and the third" ; do
einfo "This is ${myvar}"
done
for (( i = 1 ; i <= 10 ; i++ )) ; do
einfo "i is ${i}"
done
while hungry ; do
eat_cookies
done
Bash中的變量操作
在bash中,關(guān)于${}
結(jié)構(gòu),在一些情況下可以用來操作變量或者獲取變量的信息。使用這個特性可以避免相對來說比較耗性能的(或者illegal的)sed
系列指令。
獲取字符串長度
${#somevar}
可以用來獲取字符串的長度
somevar="Hello World"
echo "${somevar} is ${#somevar} characters long"
變量的默認(rèn)值
Bash中有很多的方法來為未設(shè)置或者空的變量設(shè)置一個默認(rèn)值。${var:-value}
這個結(jié)構(gòu),在var
未設(shè)置或者為空的時候為var
提供默認(rèn)值value
。${var-value}
的功能基本是相同的,但是如果var
這個變量被聲明了,但是為空,此時兩者的表現(xiàn)會不同:
var= # declared but not set
echo ${var:-default} # var獲得默認(rèn)值default
var2= # declared but not set
echo ${var2-default} # var仍為空
${var:=value}
和${var=value}
在var
沒有設(shè)置值時(null
)為其填充value
值。冒號的作用和上面的是一樣的。
${var:?message}
這個命令,會在var
這個變量未設(shè)置或者為空時,顯示message
的信息并終止程序。這里也有去掉冒號的形式${var?message}
.
${var:+value}
命令作用恰好想法,如果var
有值了,則返回value
,否則返回空字符串。
提取substring
提取substring,主要是使用到${var:offset}
和${var:offset:length}
,這兩個命令。其中offset
參數(shù)的作用方式和python是類似的,當(dāng)offset
為正數(shù)時,偏移量從左至右算,為負(fù)數(shù)時從右至左算。
Command Substitution
$(command)
這個命令可以將command
命令的stdout
輸出捕獲并返回為一個字符串。
注意:
\
command`也可以起到類似的作用,但是你最好還是使用
$(command)`,畢竟后者更加簡潔可讀,也方便嵌套使用。
字符串替換
Bash中一共提供了三種字符串替換的方式: ${var#pattern}
,${var%pattern}
,${var/pattern/replacement}
。前兩個用來進行刪除操作。
${var#pattern}
命令會返回將var
的,從字符串其實處開始的符合pattern
的最短的子字符串刪除之后余下的結(jié)果,如果沒有匹配的,則返回var
本身。如果要刪除最長的子字符串,使用${var##pattern}
${var%pattern}
類似,不過子字符串從字符串尾部算起。相應(yīng)的,如果想用貪心模式,重復(fù)百分號即可${var%%pattern}
。
${var/pattern/replacement}
可以用replacement
替換第一個匹配項。如果想要替換所有的匹配項 ,就需要使用${var//pattern/replacement}
Bash的代數(shù)計算擴展
$(( expression))
這個機構(gòu)提供了代數(shù)計算的擴展,其中expression
表達(dá)式有著類C的結(jié)構(gòu)。下面是你可以采用操作符,他們的定義基本是和C語言是一樣的:
Operators | Effect |
---|---|
var++, var-- | Variable post-increment, post-decrement |
++var, --var | Variable pre-increment, pre-decrement |
-, + | Unary minus and plus |
!, ~ | Logical negation, bitwise negation |
** | Exponentiation |
*, /, % | Multiplication, division, remainder |
+, - | Addition, subtraction |
<<, >> | Left, right bitwise shifts |
<=, >=, <, > | Comparison: less than or equal to, greater than or equal to, strictly less than, strictly greater than |
==, != | Equality, inequality |
& | Bitwise AND |
^ | Bitwise exclusive OR |
| | Bitwise OR |
&& | Logical AND |
| | | Logical OR |
expr ? expr : expr | Conditional operator |
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, | = | Assignment |
expr1 , expr2 | Multiple statements |
|