Shell script if, for, and while statements

Source: Internet
Author: User

(1) If statement

[Email protected]:/mnt/shared/shellbox/shellif# cat shellif.sh #!/bin/bash# judgment string if ["$" = "Hello"]then        echo "\$1= $ "fi# judgment number, if () mode can only be used under bash, not under sh if (>) then        echo" \$1: $ > "elif (($ = =) then        echo" \ "= =" Elif (<) then        echo "\$1 <" fi# square brackets judgment statement if [$1-lt]then        echo "\$1 <" elif [$1-g E 20-a $1-le]then        echo "\$1 >= && \$1 <=" elif [$1-gt]then        echo "\$1 >" fi

Execution Result:

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


(2) For statement

[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

Execution Result:

[Email protected]:/mnt/shared/shellbox/shellfor#./shellfor.sh
A
B
C
1
2
3


(3) While statement:

[Email protected]:/mnt/shared/shellbox/shellwhile# cat shellwhile.sh #!/bin/bash# Note: (()) This method can only be used in bash, not in SH i= 0while ((I < $))    do echo "i= $i" let    i+=1done# no spaces before or after "=" Num=0while [[$num! =]]do        echo "num= $num, N Um! = \$1 "Let        num+=1donewhile Truedo echo" here in while        true ... "        sleep 2done
Execution Result:



[Email protected]:/mnt/shared/shellbox/shellwhile#./shellwhile.sh 5
I=0
I=1
i=2
I=3
I=4
num=0, num! = $
Num=1, num! = $
num=2, num! = $
num=3, num! = $
num=4, num! = $
Here on while true ...
Here on while true ...

If, for, and while statements of the shell script

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.