Shell脚本的控制语句

一、if语句

1、简单的if语句

#!/bin/bash

if [ $# = 0 ];then                     #  [ ] 括号中必须使用空格,$#参数个数
     echo "no parameter."
     exit 1
fi
echo $#
exit
执行脚本结果:

# ./test.sh
no parameter.

# ./test.sh abc
1 

2、if else 语句

#!/bin/bash

if [ $1 -lt 0 ];then                      #  $1第一个参数
    echo Negative Number.
else
    echo Nonnegative Number.
fi
exit 
执行脚本结果:

# ./test.sh 1
Nonnegative Number.

# ./test.sh -1
Negative Number.

二、case语句

case 变量 in

  模式1)

           语句块1

           ;;

  模式2)

           语句块2

           ;;

   ........

esac



#!/bin/bash

while true                                  #死循环等待输入
do
    echo "please enter yes or no?"
    read RST
    case "$RST" in 
        y|yes)                               # 输入 y 或 yes
            echo "you enter yes."
            break                             #跳出while
            ;;
        n|no)
            echo "you enter no."
            break
            ;;
        *)
            echo "you enter error."
            ;;
    esac
done
脚本执行结果:

# ./test.sh 
please enter yes or no?
r
you enter error.
please enter yes or no?
y
you enter yes.

# ./test.sh
please enter yes or no?
n
you enter no.

三、for语句

for 变量 in 列表

do

    语句块

done

#!/bin/bash

i=0
for i in 1 2 3 4 5 6 7 8 9 
do
    if [ $i = 5 ];then
        continue
    fi
    echo "LOOP="$i
done
执行结果:

# ./test.sh
LOOP=1
LOOP=2
LOOP=3
LOOP=4
LOOP=6
LOOP=7
LOOP=8
LOOP=9

#!/bin/bash

for loop in $*                #  $*参数列表
do
	echo $loop
done

执行结果:

# ./test.sh a b c d
a
b
c
d

四、while语句

while 条件测试

do

    语句块

done

#!/bin/bash

i=0
while [ $i -lt 5 ]
do
    if [ $i = 4 ];then
        break                   #跳出循环
    fi
    echo "loop:"$i
    ((i++))
done

执行结果:

# ./test.sh
loop:0
loop:1
loop:2
loop:3

#具体的测试条件,可以man test查看

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值