接著上一篇shell變量繼續往下說:
Shell中是不支持簡單數學運算的,比如這樣:
<code>[root@VM_0_11_centos ~]# rest=10+10
[root@VM_0_11_centos ~]# echo $rest
10+10/<code>
但是我們可以加上命令使其支持,在shell中有三種弄方法可以支持簡單的數學運算:
- 使用$(())
這個$後面是兩個小括號,一個小括號不對:
<code>[root@VM_0_11_centos ~]# rest=$((10+20))
[root@VM_0_11_centos ~]# echo $rest
30
[root@VM_0_11_centos ~]# rest=$(10+20)
-bash: 10+20: command not found/<code>
- 使用$[]
使用$[]這個感覺是最簡單的
<code>[root@VM_0_11_centos ~]# rest=$[10 + 10]
[root@VM_0_11_centos ~]# echo $rest
20/<code>
3.使用關鍵字expr使用這個expr有點複雜,在使用的時候需要用反單引號將其包裹起來,而且必須有空格:
<code>[root@VM_0_11_centos ~]# rest=`expr 10 + 20`
[root@VM_0_11_centos ~]# echo $rest
30/<code>
如果沒有空格的話:
<code>[root@VM_0_11_centos ~]# rest=`expr 10+20`
[root@VM_0_11_centos ~]# $rest
-bash: 10+20: command not found/<code>
而且還不支持括號,並且乘號還要用反斜槓給轉譯一下:
<code>[root@VM_0_11_centos ~]# rest=`expr 10 + 20 \\* (10 + 10)`
-bash: command substitution: line 1: syntax error near unexpected token `('
-bash: command substitution: line 1: `expr 10 + 20 \\* (10 + 10)'
[root@VM_0_11_centos ~]# /<code>
所以遇到複雜的運算,需要一步一步的算,很麻煩!
還有一些其他的簡單運算 比如乘除,取餘等都類似
關係運算:一般用條件語句上,需要用到[]和(())比如 大於 在[]中要用-gt表示 ,在(())用==表示,gt是 greater than的縮寫例如 在文件中寫入:
<code>if (($1 > $2))
then
echo "$1 大於 $2"
else
echo "$1 小於 $2"
fi
if [ $1 -gt $2 ]
then
echo "$1 大於 $2"
else
echo "$1 小於 $2"
fi/<code>
執行:
<code>[root@VM_0_11_centos shell]# ./myShell.sh 100 200
100 小於 200
100 小於 200/<code>
shell的if語句也挺奇怪,if 之後是換行,然後then 最後需要加上fi,表示結束。 如果多個判斷的話用elif,不是else if,跟java還是有區別的需要注意的一點的是[]中括號使用的時候,一定要主要前後的空格,否則會報錯的。
其他的關係運算類似:-eq 表示相等,在(())用 ==表示,是equal的縮寫-ne表示不相等,在(())用 !=表示,是 not equal的縮寫-gt 表示大於,在(())用 >表示,是greater than的縮寫-ge 表示大於等於,在(())用 >=表示,是greater equall的縮寫-lt 表示小於,在(())用
邏輯運算符 邏輯運算符,一般是指與或非在shell []中 -a表示與,就是兩個表達式都成立,條件才成立,在(())表示為&&-o或運算,表示兩個條件只要有一個為真即可,在(()))表示為||!表示非 在(()))表示為!
字符串運算符= 檢測兩個字符串是否相等,相等則返回true != 檢測兩個字符串是否相等,不相等則返回true-z 檢測字符串長度是否為0,為0則返回true-n 檢測字符串長度是否為0,不為0則返回true str 檢測字符串是否為null,不為null則返回true
比如:
<code>str="abcdee"
if [ $str = "abc" ]
then
echo "相等"
else
echo "不相等"
fi
if [ -n $str ]
then
echo "不為0"
else
echo "為0"
fi/<code>
執行結果:
<code>[root@VM_0_11_centos shell]# ./myShell.sh
不相等
不為0/<code>
文件檢測運算符:
-b 檢測文件是否是塊設備文件,如果是,則返回true -c 檢測文件是否是字符設備文件,如果是,則返回true -d 檢測文件是否是目錄文件,如果是,則返回true -f 檢測文件是否是普通文件(既不是目錄也不是設備文件),如果是,則返回true -g 檢測文件是否設置了SGID位,如果是,則返回true -k 檢測文件是否設置了粘著位(stucky Bit),如果是,則返回true -p 檢測文件是否具名管道,如果是,則返回true -u 檢測文件是否設置了SUID位,如果是,則返回true -r 檢測文件是否可讀,如果是,則返回true -w 檢測文件是否可寫,如果是,則返回true-x 檢測文件是否可執行,如果是,則返回true -s 檢測文件是否為不為空(文件大小是否不為0),如果不為0,則返回true -e 檢測文件(包括目錄)是否存在,如果存在,則返回true -a 檢測文件(包括目錄)是否存在,如果存在,則返回true
比如檢測文件是否存在用-e 比如創建一個文件test.txt
<code>file=/root/training/shell/test.txt
if [ -e $file ]
then
echo "文件存在"
else
echo "文件不存在"
fi/<code>
執行的結果:
<code>[root@VM_0_11_centos shell]# ./myShell.sh
文件存在/<code>
未完待續!
參考文章:
https://blog.csdn.net/yuki5233/article/details/81166509
https://www.runoob.com/linux/linux-shell-basic-operators.html
閱讀更多 浩渺煙波 的文章