shell編程 筆記3 --簡單結構化命令

1.if-then語句

  • 例:
#!/bin/bash
cmd="cdss"      #等號兩邊都不能有空格
if type ${cmd}
then
    echo command ${cmd} is supported
else
    echo command ${cmd} if not supported
fi
echo $cmd
  • 注意下面這樣寫是錯的(命令退出狀態碼以外條件的測試見下節):
if $[2 > 1]     #$[2 > 1]是一個表達式,並不是一條語句

2.條件測試(兩種寫法)

    1. test命令
if test $[2>1];then
    echo "right"
fi
  • 2.中括號
if test $[ 2 > 1 ]   #注意這裏中括號和>號旁邊都加了空格
#if [ 2 \> 1 ]   #注意這裏用了\,不然會被被當成重定向符
#if [ 2 -eq 2 ]    這個寫法於上面等價
then
    echo right2
fi

test命令的數值比較功能

比較 描述 等價
n1 -eq n2 檢查 n1 是否與 n2 相等 =
n1 -ge n2 檢查 n1 是否大於或等於 n2 >=
n1 -gt n2 檢查 n1 是否大於 n2 >
n1 -le n2 檢查 n1 是否小於或等於 n2 <=
n1 -lt n2 檢查 n1 是否小於 n2 <
n1 -ne n2 檢查 n1 是否不等於 n2 !=

字符串的比較測試

比 較 描 述
str1 = str2 檢查 str1 是否和 str2 相同
str1 != str2 檢查 str1 是否和 str2 不同
str1 < str2 檢查 str1 是否比 str2 小
str1 > str2 檢查 str1 是否比 str2 大
-n str1 檢查 str1 的長度是否非0
-z str1 檢查 str1 的長度是否爲0

文件比較

比 較 描 述
-d file 檢查 file 是否存在並是一個目錄
-e file 檢查 file 是否存在
-f file 檢查 file 是否存在並是一個文件
-r file 檢查 file 是否存在並可讀
-s file 檢查 file 是否存在並非空
-w file 檢查 file 是否存在並可寫
-x file 檢查 file 是否存在並可執行
-O file 檢查 file 是否存在並屬當前用戶所有
-G file 檢查 file 是否存在並且默認組與當前用戶相同
file1 -nt file2 檢查 file1 是否比 file2 新
file1 -ot file2 檢查 file1 是否比 file2 舊

3.複合測試

#!/bin/bash
num=-2
if [ $num \< 8 ] && [ $num \> 6 ]
then
    echo num = 7
elif [ $num \< 0 ] || [ $num \< -1 ]
then
    echo num is negative
fi

4.if-then的高級特性

  • 1.雙括號命令提供了更多的數學符號
符 號 描 述
val++ 後增
val– 後減
++val 先增
–val 先減
! 邏輯求反
~ 位求反
** 冪運算
<< 左位移
>> 右位移
& 位布爾和
| 位布爾或
&& 邏輯和
|| 邏輯或

例如:

#!/bin/bash
# using double parenthesis
val1=10
if (( $val1 ** 2 > 90 ))
then
(( val2 = $val1 ** 2 ))
echo "The square of $val1 is $val2"
fi
  • 2.雙方括號命令提供了針對字符串比較的高級特性

除了test 命令中採用的標準字符串比較,還提供模式匹配(不過需要注意不是所有shell都支持[[]] )

例如:

#!/bin/bash
if [[ $USER == r* ]];then   #注意這裏使用的==,它將右邊視爲一個模式
    echo "Hello $USER"
else
    echo "Sorry, I do not know you"
fi

5.case命令

#!/bin/bash
case $USER in
hzq)
    echo "Welcome, $USER";;
testing)
    echo "Special testing account";;
*)
echo "Sorry, you are not allowed here";;
esac
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章