三分钟掌握linux shell脚本流程控制语法

 我想养一只猫。——小熊

image.png英短好好看!可惜租的房子不能养图片

流程控制

这一次我们的主题是shell脚本中的流程控制,gif动图所见即所得,语法如下。

if else

#!/bin/bash

if [ $1 == $2 ];then
  echo "a == b"
elif [ $1 -gt $2 ];then
  echo "a > b"
elif [ $1 -lt $2 ];then
  echo "a < b"
else
  echo "error"
fi


for 循环

#!/bin/bash

for loop in 1 2 3 4 5
do
   echo "The value is: $loop"
done

image.png


while 循环

#!/bin/bash
i=0
while [[ $i<3 ]]
do
   echo $i
   let "i++"
done

输出

image.png

while的判断条件可以从键盘输入,成为交互式的脚本

#!/bin/bash
echo 'press <CTRL-D> exit'
while read num
do
   echo "you input is $num"
done

ps: until循环与while循环相反,until直到判断条件为真才停止,语法同while完全一样就不多介绍了。


死循环

while true
do
   command
done

或者

for (( ; ; ))
do
   command
done

死循环,使用Ctrl+C退出。


跳出循环

就是continuebreak

case

#!/bin/bash
case $1 in
   1) echo 'You have chosen 1'
   ;;
   2) echo 'You have chosen 2'
   ;;
   *) echo 'You did not enter a number between 1 and 2'
   ;;
esac

image.png

同编程语言中的switch一样,只有语法略微不同 ,esaccase的结束符。

每个模式,用右括号结束),如果没有任何匹配的就用*),每个模式用;;两个分号连一起结束。

case 值 in
模式1)
   command1
   command2
   ...
   commandN
   ;;
模式2)
   command1
   command2
   ...
   commandN
   ;;
esac




猜你喜欢

转载自blog.51cto.com/15076235/2608311
今日推荐