国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Linux > 正文

Linux shell腳本編程if語句的使用方法(條件判斷)

2019-10-26 18:37:42
字體:
來源:轉載
供稿:網友

if 語句格式
if  條件
then
 Command
else
 Command
fi        別忘了這個結尾
If語句忘了結尾fi
test.sh: line 14: syntax error: unexpected end of fi     if 的三種條件表達式

if
command
then if
 函數
then
 命令執行成功,等于返回0 (比如grep ,找到匹配)
執行失敗,返回非0 (grep,沒找到匹配)
if [ expression_r_r_r  ]
then    表達式結果為真,則返回0,if把0值引向then
if test expression_r_r_r
then   表達式結果為假,則返回非0,if把非0值引向then      
   [ ] &&  ——快捷if
[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors"
   && 可以理解為then
    如果左邊的表達式為真則執行右邊的語句       shell的if與c語言if的功能上的區別

 shell if      c語言if
0為真,走then   正好相反,非0走then
 不支持整數變量直接if
必須:if [ i –ne 0 ] 但支持字符串變量直接if
if [ str ] 如果字符串非0
 支持變量直接if
if (i ) 


 以多條command或者函數作為if 條件
代碼如下:
echo –n “input:”
read user if
多條指令,這些命令之間相當于“and”(與)
grep $user /etc/passwd >/tmp/null     
who -u | grep $user
then             上邊的指令都執行成功,返回值$?為0,0為真,運行then
 echo "$user has logged"
else     指令執行失敗,$?為1,運行else                           
 echo "$user has not logged"
fi  
# sh test.sh
input : macg
macg     pts/0        May 15 15:55   .          2075 (192.168.1.100)
macg has logged

# sh test.sh
input : ddd
ddd has not logged       以函數作為if條件  (函數就相當于command,函數的優點是其return值可以自定義)

if
以函數作為if條件,
getyn
then   函數reture值0為真,走then
echo " your answer is yes"
else  函數return值非0為假,走else
echo "your anser is no"
fi      if command  等價于 command+if $?

$ vi testsh.sh
#!/bin/sh if
cat 111-tmp.txt | grep ting1
then
echo found
else
echo "no found"
fi
 $ vi testsh.sh
#!/bin/sh cat 111-tmp.txt | grep ting1
if [ $? -eq 0 ]
then
echo $?
echo found
else
echo $?

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南安市| 项城市| 余江县| 高雄市| 柯坪县| 松江区| 武宁县| 稷山县| 孟村| 班玛县| 汤阴县| 长治县| 云和县| 安顺市| 玛曲县| 三河市| 赣榆县| 丹巴县| 内乡县| 南靖县| 旬邑县| 鹤岗市| 汉源县| 洞口县| 荣成市| 建宁县| 鱼台县| 青田县| 大足县| 武邑县| 虎林市| 无锡市| 驻马店市| 扎鲁特旗| 饶河县| 茂名市| 含山县| 普兰店市| 通城县| 华池县| 南投县|