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

流程控制

本文章原创首发于公众号:编程三分钟shell

这一次咱们的主题是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

输出bash

while的判断条件能够从键盘输入,成为交互式的脚本编程语言

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

ps: until循环与while循环相反,until直到判断条件为真才中止,语法同while彻底同样就很少介绍了。oop

死循环

while true

do

    command

done

或者code

for (( ; ; ))
do
    command
done

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

跳出循环

就是continuebreakinput

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

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

每一个模式,用右括号结束),若是没有任何匹配的就用*),每一个模式用;;两个分号连一块儿结束。class

case 值 in

模式1)

    command1

    command2

    ...

    commandN

    ;;

模式2)

    command1

    command2

    ...

    commandN

    ;;

esac

image.png

相关文章
相关标签/搜索