Shell脚本的控制语句

来源:互联网 发布:mac两个窗口并列 编辑:程序博客网 时间:2024/05/22 04:06

一、if语句

1、简单的if语句

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

# ./test.shno parameter.# ./test.sh abc1 

2、if else 语句

#!/bin/bashif [ $1 -lt 0 ];then                      #  $1第一个参数    echo Negative Number.else    echo Nonnegative Number.fiexit 
执行脚本结果:

# ./test.sh 1Nonnegative Number.# ./test.sh -1Negative Number.

二、case语句

case 变量 in

  模式1)

           语句块1

           ;;

  模式2)

           语句块2

           ;;

   ........

esac



#!/bin/bashwhile 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."            ;;    esacdone
脚本执行结果:

# ./test.sh please enter yes or no?ryou enter error.please enter yes or no?yyou enter yes.# ./test.shplease enter yes or no?nyou enter no.

三、for语句

for 变量 in 列表

do

    语句块

done

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

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

#!/bin/bashfor loop in $*                #  $*参数列表doecho $loopdone

执行结果:

# ./test.sh a b c dabcd

四、while语句

while 条件测试

do

    语句块

done

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

执行结果:

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

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

0 0
原创粉丝点击