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命令,常用參數如下:
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 ] 中每個符號中間均需隔一個空格,否則會出錯。

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.


發佈了45 篇原創文章 · 獲贊 18 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章