一、if語句
? ? 1. if
if 語句語法格式:
if condition then ????command1 ????command2 ????... ????commandN fi |
? ? ?1)判斷當(dāng)前系統(tǒng)是否有多個ssh進(jìn)程,如果有則打印true
test12.sh
#!/bin/bash if?[?$(ps -ef | grep -c "ssh")?-gt 1?] then? ?echo?"true"? fi文章來源地址http://www.zghlxwxcb.cn/news/detail-831317.html |
? ? ? 2)判斷/media/cdrom文件是否存在,若不存在就去創(chuàng)建這個目錄
test13.sh
#!/bin/bash? DIR="/media/cdrom"? if?[?!?-e?$DIR?]? then? mkdir?-p $DIR? fi |
? 2.?if else
if else 語法格式:
if condition then ????command1 ????command2 ????... ????commandN else ????command fi |
實(shí)例:
? ? ? ? 1)根據(jù)年齡判斷是否成年
test14.sh
#!/bin/bash read?-p "Enter your age(1-100):"?age if?[?$age?-ge 18?] then ?????echo?'已經(jīng)成年!' else ?????echo?'未成年!' fi |
? ? ?2)if else語句經(jīng)常與test命令結(jié)合使用
test 命令允許你做各種測試并在測試成功或失敗時返回它的退出狀態(tài)碼(為0表示為真,為1表示為假)。使用這個狀態(tài)碼,可以讓?Bash?對測試的結(jié)果做出反應(yīng)。
test 命令的語法為:
test EXPRESSION
或
[ EXPRESSION ]
test15.sh
#!/bin/bash num1=$[2*3] num2=$[1+5] if?test?$[num1]?-eq $[num2] then ????echo?'兩個數(shù)字相等!' else ????echo?'兩個數(shù)字不相等!' fi |
? ? ? ???????3.if else-if else
if else-if else 語法格式:
if condition1 then ????command1 elif condition2 then ????command2 else ????commandN fi |
實(shí)例:
? ? ? 1)以下實(shí)例判斷兩個變量是否相等:
test16.sh
#!/bin/bash? echo?"請輸入a的值:"? read?a echo?"請輸入b的值:"? read?b if?[?$a?==?$b?]? then? echo?"a 等于 b"? elif?[?$a?-gt $b?]? then? echo?"a 大于 b"? elif?[?$a?-lt $b?]? then? echo?"a 小于 b"? else? echo?"沒有符合的條件"? fi |
? ? ? ? 2)輸入成績,判斷成績“優(yōu)”“良”“中”
test17.sh
#!/bin/bash read?-p "Enter your score(0-100):"?n #-p參數(shù)表示給出提示信息 if?[?$n?-ge 85?]?&&?[?$n?-le 100?]?;?then ?echo?"優(yōu)" elif?[?$n?-ge 70?]?&&?[?$n?-le 84?]?;?then ?echo?"良" elif?[?$n?-ge 60?]?&&?[?$n?-le 69?]?;?then ?echo?"中" else ?echo?"差"?文章來源:http://www.zghlxwxcb.cn/news/detail-831317.html fi |
到了這里,關(guān)于Linux--shell編程中的if語句的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!