shell 指令碼之if、for、while語句

來源:互聯網
上載者:User

標籤:blog   ar   使用   for   sp   on   2014   log   bs   

(1)if語句

[email protected]:/mnt/shared/shellbox/shellif# cat shellif.sh #!/bin/bash#判斷字串if [ "$1" = "hello" ]then        echo "\$1=$1"fi#判斷數字,if()方式只能在bash下用,在sh下不行if ((  $1 > 20 ))then        echo "\$1: $1 > 20"elif (( $1 == 20 ))then        echo "\$1 == 20"elif (( $1 < 20 ))then        echo "\$1 < 20"fi#方括弧判斷語句if [ $1 -lt 20 ]then        echo "\$1 < 20"elif [ $1 -ge 20 -a $1 -le 30 ]then        echo "\$1 >= 20 && \$1 <= 30 "elif [ $1 -gt 30 ]then        echo "\$1 > 30"fi

執行結果:

[email protected]:/mnt/shared/shellbox/shellif# ./shellif.sh 10
$1 < 20
$1 < 20
[email protected]:/mnt/shared/shellbox/shellif# ./shellif.sh 20
$1 == 20
$1 >= 20 && $1 <= 30 
[email protected]:/mnt/shared/shellbox/shellif# ./shellif.sh 30
$1: 30 > 20
$1 >= 20 && $1 <= 30 
[email protected]:/mnt/shared/shellbox/shellif# ./shellif.sh 40
$1: 40 > 20
$1 > 30


(2)for語句

[email protected]:/mnt/shared/shellbox/shellfor# cat shellfor.sh #!/bin/bashfor i in $*do        echo $idonefor char in {a..c}do        echo $chardonefor int in {1..3}do         echo $intdone

執行結果:

[email protected]:/mnt/shared/shellbox/shellfor# ./shellfor.sh 
a
b
c
1
2
3


(3)while語句:

[email protected]:/mnt/shared/shellbox/shellwhile# cat shellwhile.sh #!/bin/bash#注意: (( ))這種方式只能在bash中使用,而不能在sh中使用i=0while (( i < $1 ))do    echo "i=$i"    let i+=1done#賦值時"="前後不能有空格num=0while [[ $num != $1 ]]do        echo "num=$num, num != \$1"        let num+=1donewhile truedo        echo "here in while true ..."        sleep 2done
執行結果:



[email protected]:/mnt/shared/shellbox/shellwhile# ./shellwhile.sh 5
i=0
i=1
i=2
i=3
i=4
num=0, num != $1
num=1, num != $1
num=2, num != $1
num=3, num != $1
num=4, num != $1
here in while true ...
here in while true ...

shell 指令碼之if、for、while語句

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.