If statement,case and loop(Linux)

Basic If Statements

if [ <some test> ]
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命令,常用参数如下:
OperatorDescription
! EXPRESSIONThe EXPRESSION is false.
-n STRINGThe length of STRING is greater than zero.
-z STRINGThe lengh of STRING is zero (ie it is empty).
STRING1 = STRING2STRING1 is equal to STRING2
STRING1 != STRING2STRING1 is not equal to STRING2
INTEGER1 -eq INTEGER2INTEGER1 is numerically equal to INTEGER2
INTEGER1 -gt INTEGER2INTEGER1 is numerically greater than INTEGER2
INTEGER1 -lt INTEGER2INTEGER1 is numerically less than INTEGER2
-d FILEFILE exists and is a directory.
-e FILEFILE exists.
-r FILEFILE exists and the read permission is granted.
-s FILEFILE exists and it's size is greater than zero (ie. it is not empty).
-w FILEFILE exists and the write permission is granted.
-x FILEFILE 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 ] 中每个符号中间均需隔一个空格,否则会出错。

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值