Shell 流程控制

if else

  -->if

  if 条件

  then

    command

    command

    ......

  fi

  实例

  

#!/bin/sh
a="abc"
b="def"
if [ $a != $b ]
then
        echo "true"
fi

  -->if else

  if 条件

  then

    command

    command

    ......

  else

    command

    command

    ......

  fi

  实例

  

#!/bin/sh
a="abc"
b="def"
if [ $a = $b ]
then
        echo "true"
        echo "ada"
        echo "da"
else
        echo "false"
        echo "123"
fi

  -->if else-if else

  if 条件

  then  

    command

    command

    ......

  elif 条件

  then

    command

    command

    ......

  else

    command

    ......

  fi

  实例

  

#!/bin/sh
a=10
b=20
if [ $a -eq $b ]
then
        echo "a!=b"
elif [ $a -gt $b ]
then
        echo "a>b"
else
        echo "a<b"
fi
for循环

  格式:

    for var in it1 it2 it3 ...

    do  

      command

      command

      ...

   done

  说明:in列表可以包括替换,字符串,文件名等。

  实例

  

#!/bin/sh
for i in 1 2 3 4 5
do
        echo ${i}
done


#输出结果
#    1
#    2
#    3
#    4
#    5
#!/bin/sh
for i in 'Hello world kitty'
do
        echo ${i}
done
    

#输出结果
# Hello world kitty
while语句

  格式:

    while 条件

    do 

      command

      ...

    done

  实例

#!/bin/sh
a=1
while (($a < 5 ))
do
        echo "hello"
        let "a++"  #让a加1
done


#输出结果
#hello
#hello
#hello
#hello
until循环

  说明:until 循环执行一系列命令直至条件为 true 时停止。

  格式:

    until 条件

    do  

      command

      ...

    done

  实例:

#!/bin/sh
a=1
until [ $a -gt 5 ]
do
        echo $a
        let "a++"
done

#输出结果
#    1
#    2
#    3
#    4
#    5
case

  说明:可以用case语句匹配一个值与一个模式,如果匹配成功,执行相匹配的命令。

  格式:

    case 数值 in 

    模式1)

      command

      command

      ...

      ;;

    模式2)

      command

      command

      ...

      ;;

    ....

    esac  

  实例:

    

#!/bin/sh
echo "请输入一个数字"
read a
case $a in
1)
        echo "hello"
        echo "world"
        ;;
2)
        echo "world"
        echo "hello"
        ;;
esac

输出结果:

  输入1:输出hello  

        world

  输入2:输出world  

       hello

break和continue

  我们用例子来理解其用法

  break实例:

for i in 1 2 3 4 5
do
        if [ $i -eq 3 ]
        then
                break
        else
                echo ${i}
        fi
done

#输出结果
#    1
#    2

  

  continue实例:

  

#!/bin/sh
for i in 1 2 3 4 5
do
        if [ $i -eq 3 ]
        then
                continue
        else
                echo ${i}
        fi
done

#输出结果
#    1
#    2
#    4
#    5

猜你喜欢

转载自www.cnblogs.com/lyr999736/p/9024295.html