Shell流程控制


While循环简单案例:

 while语句结构

    while 条件语句
    do
    action
    done;

    实例1:
    #!/bin/sh
    i=10;
    while [[ $i -gt 5 ]];do
        echo $i;
        ((i--));
    done;

    运行结果:========================
    sh while1.sh
    10
    9
    8
    7
    6

实例2:(循环读取文件内容:)

#!/bin/sh
while read line;do
echo $line;
done < /etc/Monkey.sh;
运行结果:===================
sh while2.sh
# Do not remove the following line, or various programs
# that require network functionality will fail.


实例3:while循环可用于读取键盘信息。

echo '按下  退出'
echo -n '输入你最喜欢的电影名: '
while read FILM
do
    echo "是的!$FILM 是一部好电影"
done


if命令

if 语句语法格式:
if condition
then
    command1
    command2
    ...
    commandN
fi

写成一行(适用于终端命令提示符):
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo"true"; fi


if else if else-if else结合使用

a=10
b=20
if [ $a == $b ]
then
   echo "a 等于 b"
elif [ $a -gt $b ]
then
   echo "a 大于 b"
elif [ $a -lt $b ]
then
   echo "a 小于 b"
else
   echo "没有符合的条件"
fi


if else语句经常与test命令结合使用,如下所示:

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo '两个数字相等!'
else
    echo '两个数字不相等!'
fi
 
输出结果:
两个数字相等!

for 循环

数组遍历

for i in *
do
       echo $i
done
!
: <

另一种遍历方式

ls > ls.txt
for i in $(cat ls.txt)
do
       echo $i
done
!

函数传递

#注意 $@ 加上引号和不加是有区别的

nubset()
{
       for str in "$@"
       do
              echo $str
       done

}
nubset 1 2 3 4
nubset 1,2,3,4
nubset "this is nub"
nubset "this2,is2,nub2"
nubset we will be fine


自然数的遍历使用 {}

for i in {1..5}
do
       echo "go $i home"
done
 
for i in {0..10..2}
do
    echo "go $i home"
done
 

经典循环
for (( i = 0; i < 10; i++ ))
do
       echo $i
done

以上代码均经过测试,可用,点击进入 原创地址

 

复合型实例

nub=(137 237 337 437 537  637)
employee=(小明 小张 小红 小王 小竹 小胡)
setnub=6
: <


--------------------------------------无限循环命令------------------

 

:<

until命令

until循环执行一系列命令直至条件为真时停止。

until循环与while循环在处理方式上刚好相反。

一般while循环优于until循环,但在某些时候—也只是极少数情况下,until循环更加有用。

until 语法格式:

until condition
do
    command
done

Case

#--下面的脚本提示输入1到4,与每一种模式进行匹配: ---

: <

 #---跳出循环------------break跳出后续循环---------------------------------

: <

#---跳出循环------------continue---------------------------------

 

: <

你可能感兴趣的:(Shell)