Skip to content

流程控制

1. if 判断

基本语法

  1. 单分支
sh
if [ 条件判断式 ];then
    程序
fi

或者

sh
if [ 条件判断式 ]
then
    程序
fi
sh
## 字符串比较, 除了使用eq之外还可以用=
[root@hadoop100 shell_learn]# cat test.sh 
#!/bin/bash

if [ $1 = "jack" ];then
    echo "welcome, jack"
fi
[root@hadoop100 shell_learn]# ./test.sh jack
welcome, jack
[root@hadoop100 shell_learn]# ./test.sh
./test.sh: 3 行:[: =: 期待一元表达式
## 可以没输入的时候避免报错,这么写:
[root@hadoop100 shell_learn]# cat test.sh 
#!/bin/bash

if [ "$1"x = "jack"x ];then
    echo "welcome, jack"
fi
## 多个判断
[root@hadoop100 shell_learn]# a=25
[root@hadoop100 shell_learn]# if [ $a -gt 18 ] && [ $a -lt 35 ];then echo 'ok';fi
ok

2. 多分支

sh
if [ 条件判断式 ]
then
    程序
elif [ 条件判断式 ]
then
    程序
else
    程序
fi

警告

  1. [ 条件判断式 ],中括号和条件判断式之间必须有空格
  2. ifelif 后要有空格
sh
[root@hadoop100 shell_learn]# cat test.sh 
#!/bin/bash

if [ "$1"x = "jack"x ];then
 echo "welcome, jack"
fi

if [ $2 -lt 18 ] then
    echo '未成年人'
elif [ $2 -lt 60 ] then 
    echo '中年人'
elif [ $2 -lt 80]
then 
    echo '老年人'
else
    echo '请提供年龄'
fi
[root@hadoop100 shell_learn]# ./test.sh jack 33
welcome, jack
中年人

3. case 语句

基本语法

sh
case $变量名 in
"值 1")
    如果变量的值等于值 1,则执行程序 1
;;
"值 2")
    如果变量的值等于值 2,则执行程序 2
;;
…省略其他分支…*)
    如果变量的值都不是以上的值,则执行此程序
;;
esac

警告

(1)case 行尾必须为单词"in",每一个模式匹配必须以右括号")"结束。
(2)双分号";;"表示命令序列结束,相当于 java 中的 break。
(3)最后的"*)"表示默认模式,相当于 java 中的 default。

sh
[root@hadoop100 shell_learn]# cat case_test.sh 
#!/bin/bash

case $1 in
1) 
    echo 'one'
;;
2)
    echo 'two'
;;
3)
    echo 'three'
;;
*)     
    echo 'number else'
;;
esac
[root@hadoop100 shell_learn]# ./case_test.sh 2
two

4. for 循环

基本语法

sh
for (( 初始值;循环控制条件;变量变化 ))
do
    程序
done

或者

for 变量 in 值 1 值 2 值 3…
do
    程序
done
sh
[root@hadoop100 shell_learn]# cat for_test.sh 
#!/bin/bash

for ((i=1; i<=$1; i++ ))
do
    sum=$[ $sum + $i ]
done
echo $sum
[root@hadoop100 shell_learn]# ./for_test.sh 100
5050
[root@hadoop100 shell_learn]# ./for_test.sh 10
55

其中for中可以使用<= 符合是因为for使用(())(())里面是可以写表达式的。

sh
[root@hadoop100 shell_learn]# for i in {1..100}; do sum=$[$sum+$i]; done; echo $sum;
5050

5. while 循环

基本语法

sh
while [ 条件判断式 ]
do
    程序
done
sh
##  从 1 加到 100
[root@hadoop100 shell_learn]# cat while_test.sh
#!/bin/bash

i=1
while [ $i -le $1 ]
do
    sum=$[$sum+$i]
# 最新shell支持let语法
    let sum2+=i
    i=$[$i+1]
#    let i++
done
echo $sum
echo $sum2
[root@hadoop100 shell_learn]# ./while_test.sh 100
5050
5050
[root@hadoop100 shell_learn]# ./while_test.sh 10
55
55