国产探花免费观看_亚洲丰满少妇自慰呻吟_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 $?

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜君县| 措美县| 崇左市| 多伦县| 水富县| 乌海市| 闻喜县| 泗阳县| 红原县| 乌鲁木齐市| 南部县| 中西区| 山阳县| 甘泉县| 云霄县| 泌阳县| 胶南市| 额尔古纳市| 翁牛特旗| 修文县| 巨野县| 沙田区| 汉川市| 肃北| 商河县| 文登市| 抚松县| 宜昌市| 竹溪县| 河源市| 武宣县| 德庆县| 延长县| 理塘县| 永春县| 天水市| 许昌市| 托克逊县| 彭山县| 岑巩县| 泽州县|