Basic If Statements
if [ <some test> ]
then
<commands>
fi
then
<commands>
fi
If Else
if [ <some test> ]then
<commands>
else
<other commands>
fi
If Elif Else
if [ <some test> ]then
<commands>
elif [ <some test> ]
then
<different commands>
else
<other commands>
fi
在if语句中的判定条件: [ <some test> ],实际是test命令,常用参数如下:
Operator | Description |
---|---|
! EXPRESSION | The EXPRESSION is false. |
-n STRING | The length of STRING is greater than zero. |
-z STRING | The lengh of STRING is zero (ie it is empty). |
STRING1 = STRING2 | STRING1 is equal to STRING2 |
STRING1 != STRING2 | STRING1 is not equal to STRING2 |
INTEGER1 -eq INTEGER2 | INTEGER1 is numerically equal to INTEGER2 |
INTEGER1 -gt INTEGER2 | INTEGER1 is numerically greater than INTEGER2 |
INTEGER1 -lt INTEGER2 | INTEGER1 is numerically less than INTEGER2 |
-d FILE | FILE exists and is a directory. |
-e FILE | FILE exists. |
-r FILE | FILE exists and the read permission is granted. |
-s FILE | FILE exists and it's size is greater than zero (ie. it is not empty). |
-w FILE | FILE exists and the write permission is granted. |
-x FILE | FILE exists and the execute permission is granted. |
[@entmcnode15] my_linux $ cat if_script.sh
#!/bin/bash
if [ $1 -gt 100 ]
then
echo too large
if [ $2 -gt 1 ]
then
echo second is big
fi
fi
date
[@entmcnode15] my_linux $ ./if_script.sh 110 3
too large
second is big
Mon Sep 8 16:39:11 CEST 2014
[@entmcnode15] my_linux $
解释:line 3:$1是否greater than 100? $1表示script运行时命令行输入的第一个变量,如此例中
/if_script.sh 110 3 中的110。
line 6:$2是否greater than 1? $2表示script运行时命令行输入的第2个变量,如此例中/if_script.sh 110 3 中的3。
注意:if [ $1 -gt 100 ] 中每个符号中间均需隔一个空格,否则会出错。
<pattern 1>)
<commands>
;;
<pattern 2>)
<other commands>
;;
esac
注意:if [ $1 -gt 100 ] 中每个符号中间均需隔一个空格,否则会出错。
Boolean Operations
- and - &&
- or - ||
<pre name="code" class="cpp">#!/bin/bash
# or example
if [ $USER == 'bob' ] || [ $USER == 'andy' ]
then
ls -alh
else
ls
fi
Case Statements
case <variable> in<pattern 1>)
<commands>
;;
<pattern 2>)
<other commands>
;;
esac
case.sh
#!/bin/bash
# case example
case $1 in
start)
echo starting
;;
stop)
echo stoping
;;
restart)
echo restarting
;;
*)
echo don\'t know
;;
esac
- Line 14 - The * represents any number of any character. It is essentially a catch all if for if none of the other cases match. 相当于c中的default。
While Loops
while [ <some test> ]do
<commands>
done
如图所示:
while_loop.sh
#!/bin/bash
# Basic while loop
counter=1
while [ $counter -le 10 ]
do
echo $counter
((counter++))
done
echo All done
- Line 8 - Using the double brackets we can increase the value of counter by 1.