Shell入门(四)之Shell 流程控制

Shell入门(四)之Shell 流程控制

if else

if语句

语法:

if condition
then
    command
    ...
fi

eg:

#!/bin/bash

a=100
b=100

if [ $a == $b ]
then
    echo "$a == $b"
fi

输出:

100 == 100

也可以在终端写成一行:

[zhang@localhost ~]$ a=100
[zhang@localhost ~]$ b=100
[zhang@localhost ~]$ if [ $a == $b ]; then    echo "$a == $b"; fi
100 == 100

if else语句

语法:

if condition
then
    command
    ...
else
    command
    ...
fi

eg:

在终端输入

[zhang@localhost ~]$ a=100
[zhang@localhost ~]$ b=200
[zhang@localhost ~]$ if [ $a == $b ]
> then
>     echo "$a == $b"
> else
>     echo "$a != $b"
> fi
100 != 200

if elif else语句

语法:

if condition1
then
    command1
    ...
elif comdition2
then
    command2
else
    command
fi

eg:

#!/bin/bash

a=100
b=200
c=150

if [ $[a + c] > $b ]
then
    echo "$a + $c > $b  return true"
elif [ $[a + c] < $b ]
then 
    echo "$a + $c < $b  return true"
else
    echo "$a + $c = $b  return true"
fi

输出结果:

100 + 150 > 200  return true
for循环

for语法:

for var in item1 item2 ... itemn
do
    command1
    command2
    ...
    commandn
done

写成一行:

for var in item1 item2 ... itemn; do command1;command2 ... done;

eg:

[zhang@localhost ~]$ for num in 1 2 4 8 16
> do
>     echo $num
> done
1
2
4
8
16

一行执行:

[zhang@localhost ~]$ for num in 1 2 3 4 5; do echo $num; done
1
2
3
4
5
While语句

while语法:

while condition
do
    command
done

eg:

#!/bin/bash

num=1

while(($num<=5))
do
    echo $num
    let "num++"
done

输出结果:

1
2
3
4
5

无限循环

while :
do
    command
done

或者

while true
do
    command
done

或者

for (( ; ; ))
until循环

until语法:

until condiion
do
    command
done

一般使用while替代

case

case语法:

case value in
value1)
    command1
    command2
    ...
    commandn
    ;;
value2)
    command1
    command2
    ...
    commandn
    ;;
value3)
    command1
    command2
    ...
    commandn
    ;;
*)
    command1
    command2
    ...
    commandn
    ;;
esac

;;:其间所有command执行到;;结束。相当于break

*:相当于java中的default

eg:

#!/bin/bash

value=2

case $value in
1)
    echo "$value equal 1"
    ;;
2)
    echo "$value equal 2"
    ;;
3)
    echo "$value equal 3"
    ;;
*)
    echo "$value not find"
    ;;
esac

输出结果:

2 equal 2
跳出循环

break命令

#!/bin/bash

for i in 1 2 3 4 5
do
   if [ $[i % 2] == 0 ]
   then
        echo "$i"
        break
   fi
done

输出:2

continue命令

#!/bin/bash

for i in 1 2 3 4 5
do
    if [ $[i % 2] == 0 ]
    then
        echo "$i"
        continue 
    fi
done

输出:

2
4

esac命令

与case协同使用,作为case的结束符号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值