天天看點

shell 腳本之if、for、while語句

(1)if語句

root@ubuntu:/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      

運作結果:

root@ubuntu:/mnt/shared/shellbox/shellif# ./shellif.sh 10

$1 < 20

root@ubuntu:/mnt/shared/shellbox/shellif# ./shellif.sh 20

$1 == 20

$1 >= 20 && $1 <= 30 

root@ubuntu:/mnt/shared/shellbox/shellif# ./shellif.sh 30

$1: 30 > 20

root@ubuntu:/mnt/shared/shellbox/shellif# ./shellif.sh 40

$1: 40 > 20

$1 > 30

(2)for語句

root@ubuntu:/mnt/shared/shellbox/shellfor# cat shellfor.sh 
#!/bin/bash

for i in $*
do
        echo $i
done

for char in {a..c}
do
        echo $char
done


for int in {1..3}
do 
        echo $int
done      

root@ubuntu:/mnt/shared/shellbox/shellfor# ./shellfor.sh 

a

b

c

1

2

3

(3)while語句:

root@ubuntu:/mnt/shared/shellbox/shellwhile# cat shellwhile.sh 
#!/bin/bash

#注意: (( ))這樣的方式僅僅能在bash中使用,而不能在sh中使用
i=0
while (( i < $1 ))
do
    echo "i=$i"
    let i+=1
done

#指派時"="前後不能有空格
num=0
while [[ $num != $1 ]]
do
        echo "num=$num, num != \$1"
        let num+=1
done

while true
do
        echo "here in while true ..."
        sleep 2
done