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 $?
新聞熱點
疑難解答