1.邏輯操作符舉例
提示:
!中文意思是反:與一個邏輯值相反的邏輯值。
-a中文意思是與(&&):兩個邏輯值都為真返回值才為真,反之為假。
-o中文意思是或(or):兩個邏輯值只要一個為真,返回值就為真。
結論:
真 true 1 假 false 0
(1)-a或&&(邏輯與)的運算規則:只有兩端都是1才為真相當於乘法運算。
and 1*0=0
and 0*1=0
and 1*1=1
and 0*0=0
只有兩端都是1才為真,and交集
(2)-o或||(邏輯或)的運算規則:兩端都是0才為假,任何一端不為0都是真。
or 1+0=1 真
or 1+1=2 真
or 0+1=1 真
or 0+0=0 假
兩端都是0才為假,不為0就是真。or 並集
(3)這裡有一個系統不等於的例子
例子演示:
2.實踐
(1)"-a"和 "-o",邏輯運算符號用於[]中使用。
(2)"&&"和 "||",邏輯運算符號用於[[ ]]中使用。
(3)注意括號兩端,必須要有空格。
3.系統腳本例子
4.小結:邏輯操作符使用總結
(1)[ ]中括號中使用-a,-o,!這種操作符(推薦使用)。
(2)[[ ]]雙中括號中用&&,||,!這種操作符。
(3)邏輯操作符使用test和[]中括號。
(4)多個[]之間以及多個[[ ]]之間,或者任意混合中間邏輯操作符都用&&或||。
5.綜合實例:
(1)以定義變量、腳本傳參、以及read讀入的方式比較兩個整數的大小用條件表達式(禁止用if),進行判斷並以屏幕輸出的方式提醒用戶比較結果,一共開發3個腳本。當用腳本傳參以及read讀入的方式需要對變量的值進行判斷是否為數字並且如果傳參個數不對給與用戶提示。
a.腳本傳參方式
<code>[root@shellbiancheng ~]# cat zhengshubijiao.sh #!/bin/sh #腳本傳參 [ $# -ne 2 ]&&{ echo #34;Usage :$0 {num1 and num2}" exit 1 } [[ "`echo "$1"|sed -r 's#[^0-9]##g'`" = "$1" ]]||{ echo "first arg must be int" exit 2 } [[ "`echo "$2"|sed -r 's#[^0-9]##g'`" = "$2" ]]||{ echo "first arg must be int" exit 2 } [ $1 -eq $2 ]&&{ echo "$1=$2" exit 0 } [ $1 -gt $2 ]&&{ echo "$1>$2" exit 0 } [ $1 -lt $2 ]&&{ echo "$10 [root@shellbiancheng ~]# sh zhengshubijiao.sh 1 1 1=1 [root@shellbiancheng ~]# sh zhengshubijiao.sh 1 e first arg must be int [root@shellbiancheng ~]# sh zhengshubijiao.sh e 1 first arg must be int/<code>
b.read讀入的方式
<code>[root@shellbiancheng ~]# cat zhengshubijiao1.sh #!/bin/sh read -p "please input two num:" num1 num2 c="please input two num" a=$num1;b=$num2 [ -z "$a" -o -z "$b" ]&&{ echo #34;Usage :$c{num1 and num2}" exit 1 } [[ "`echo "$a"|sed -r 's#[^0-9]##g'`" = "$a" ]]||{ echo "first arg must be int" exit 2 } [[ "`echo "$b"|sed -r 's#[^0-9]##g'`" = "$b" ]]||{ echo "first arg must be int" exit 2 } [ $a -eq $b ]&&{ echo "$a=$b" exit 0 } [ $a -gt $b ]&&{ echo "$a>$b" exit 0 } [ $a -lt $b ]&&{ echo "$a0 [root@shellbiancheng ~]# sh zhengshubijiao1.sh please input two num:1 2 1<2 [root@shellbiancheng ~]# sh zhengshubijiao1.sh please input two num:1 e first arg must be int [root@shellbiancheng ~]# sh zhengshubijiao1.sh please input two num:e 1 first arg must be int/<code>
定義變量就是將read讀入中的a和b賦值,然後將read去掉這裡我就不舉例了。
(2)打印選擇菜單,一鍵安裝web服務
要求:當用戶輸入1時,輸出“start installing lamp”然後執行/server/scripts/lamp.sh,腳本內容輸出“lamp is installed”後退出腳本;當用戶輸入2時,輸出“start installing lnmp”然後執行/server/script/lnmp.sh,輸出“lnmp is installed”後退出腳本;當輸入3時退出當前菜單及腳本。當輸入任何其他字符,給出提示“Input error”後退出腳本。要對執行的腳本進行相關條件判斷,例如:腳本是否存在,是否可執行等。打印菜單,實現web服務安裝。
<code>[root@shellbiancheng ~]# cat webmenu.sh #!/bin/bash export PATH="/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/curl/bin:/root/bin" path="/server/scripts" RETVAL=0 [ -d "$path" ]|| mkdir -p $path menu(){ cat
關鍵字: shellbiancheng exit 腳本