Linux中的流程控制语句

if语句

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

注意:
  a.使用fi结尾
  b.条件判断式和中括号之间需要有空格

[root@localhost sh]# cat if_test.sh 
#!/bin/bash
#判断系统硬盘使用率

rate=$(df -h | grep /dev/sda1 | awk '{print $5}' | cut -d "%" -f1)

if [ $rate -ge 90 ]
  then
    echo "dev/sda1 is full"
    echo "now use : $rate"
elif [ $rate -ge 80 ]
  then
    echo "dev/sda1 will be full"
    echo "now is $rate"
else
  echo "dev/sda1 is not full"
  echo "now use : $rate"
fi

[root@localhost sh]# sh if_test.sh 
dev/sda1 is not full
now use : 7
[root@localhost sh]#


case语句

case $变量名 in
  "值1")
    如果值为1就执行这里的代码
    ;;
  "值2")
    如果值为2就执行这里的代码
    ;;
  *)
    如果都匹配不上就执行这里的代码
    ;;
esac

[root@localhost sh]# cat case_test.sh 
#!/bin/bash
#判断用户输入

read -p "input yes/no: " -t 30 cho
case $cho in
  "yes")
    echo "intput is yes"
    ;;
  "no")
    echo "input is no"
    ;;
  *)
    echo "error input"
    ;;
esac

[root@localhost sh]# sh case_test.sh 
input yes/no: yes
intput is yes
[root@localhost sh]#

  

for语句

语法一:

for 变量 in 值1 值2 值3
  do
    程序
  done

[root@localhost sh]# cat for1.sh 
#!/bin/bash
#打印时间
for time in moring noon afternoon evening
  do
    echo "This time is $time"
  done

[root@localhost sh]# sh for1.sh 
This time is moring
This time is noon
This time is afternoon
This time is evening
[root@localhost sh]# 
[root@localhost sh]# cat for2.sh 
#!/bin/bash
#打印文件名
ls > ls.log
for f in $(cat ls.log)
  do
    echo "File is $f"
  done

[root@localhost sh]# sh for2.sh 
File is case_test.sh
File is for1.sh
File is for2.sh
File is if_test.sh
File is ls.log
File is param_test1.sh
File is param_test2.sh
File is param_test3.sh
[root@localhost sh]#

语法二:

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

[root@localhost sh]# cat for3.sh 
#!/bin/bash
#从1加到100
s=0
for((i=1;i<=100;i++))
  do
    s=$(($s+$i))
  done

echo "Sum $s"
[root@localhost sh]# sh for3.sh 
Sum 5050
[root@localhost sh]#

while循环
while [条件判断式]
  do
    程序
  done

[root@localhost sh]# cat while_test.sh 
#!/bin/bash
#从1到100累加
i=1
s=0
while [ $i -le 100 ]
  do
    s=$(($s+$i))
    i=$(($i+1))
  done
echo "Sum $s"
[root@localhost sh]# sh while_test.sh 
Sum 5050
[root@localhost sh]#

  

until循环
until [条件判断式]
  do
    程序
  done

[root@localhost sh]# cat until_test.sh 
#!/bin/bash
#从1到100累加
i=1
s=0
until [ $i -gt 100 ]
  do
    s=$(($s+$i))
    i=$(($i+1))
  done
echo "Sum $s"
[root@localhost sh]# sh until_test.sh 
Sum 5050
[root@localhost sh]#

  

原文地址:https://www.cnblogs.com/413xiaol/p/7192369.html