[root@hadoop100 shell]# cat if.sh #!/bin/bash # 使用字符串的拼接阻止程序报错 if [ "$1"x = "1"x ] then echo "num is one" elif [ "$1"x = "2"x ] then echo "num is two" else echo "others" fi [root@hadoop100 shell]# ./if.sh 1 num is one [root@hadoop100 shell]# ./if.sh 2 num is two [root@hadoop100 shell]# ./if.sh 3 others [root@hadoop100 shell]# ./if.sh others
1.4 经验汇总
当需要合并分支进行判断时,可以使用 -a,同时对2个条件进行判断
1 2 3
[root@hadoop100 shell]# a=19 [root@hadoop100 shell]# if [ $a -gt 18 -a $a -lt 30 ];then echo "young" ; fi young
[root@hadoop100 shell]# ./case.sh 1 one [root@hadoop100 shell]# ./case.sh 2 two [root@hadoop100 shell]# ./case.sh 3 others
三:for 循环
3.1 基本语法
1 2 3 4
for (( 初始值;循环控制条件;变量变化 )) do 程序 done
1 2 3 4
for 变量 in 值 1 值 2 值 3… do 程序 done
3.2 案例实操
1 2 3 4 5 6 7 8 9
[root@hadoop100 shell]# cat sum.sh #!/bin/bash for (( i=0;i<=100;i++ )) do sum=$[$sum+$i] done echo $sum [root@hadoop100 shell]# ./sum.sh 5050
1 2 3 4 5 6 7 8 9 10
[root@hadoop100 shell]# cat foreach.sh #!/bin/bash for i in 12 18 24 do echo "num is $i" done [root@hadoop100 shell]# ./foreach.sh num is 12 num is 18 num is 24
[root@hadoop100 shell]# cat diff.sh #!/bin/bash echo '=== $* ===' for i in $* do echo "letter is $i" done
echo '=== $@ ==='
for i in $@ do echo "letter is $i" done [root@hadoop100 shell]# ./diff.sh 123 qwe 456 === $* === letter is 123 letter is qwe letter is 456 === $@ === letter is 123 letter is qwe letter is 456
[root@hadoop100 shell]# cat diff.sh #!/bin/bash echo '=== $* ===' for i in "$*" do echo "letter is $i" done
echo '=== $@ ==='
for i in "$@" do echo "letter is $i" done [root@hadoop100 shell]# ./diff.sh 123 qwe 456 === $* === letter is 123 qwe 456 === $@ === letter is 123 letter is qwe letter is 456