shell学习六流程控制

1.条件语句 condition 用[ ] 或是test

if else

if

if 语句语法格式:编程

if condition
then
    command1 
    command2
    ...
    commandN 
fi

if else-if else

if else-if else 语法格式:编程语言

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

for 循环

与其余编程语言相似,Shell支持for循环。测试

for循环通常格式为:spa

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

while 语句

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令一般为测试条件。其格式为:it

while condition
do
    command
done

如下是一个基本的while循环,测试条件是:若是int小于等于5,那么条件返回真。int从0开始,每次循环处理时,int加1。运行上述脚本,返回数字1到5,而后终止。io

#!/bin/sh
int=1
while(( $int<=5 ))
do
        echo $int
        let "int++"
done

case

Shell case语句为多选择语句。能够用case语句匹配一个值与一个模式,若是匹配成功,执行相匹配的命令。case语句格式以下:for循环

case  in
模式1)
    command1
    command2
    ...
    commandN
    ;;
模式2
    command1
    command2
    ...
    commandN
    ;;
esac

case工做方式如上所示。取值后面必须为单词in,每一模式必须以右括号结束。取值能够为变量或常数。匹配发现取值符合某一模式后,其间全部命令开始执行直至 ;;。test

取值将检测匹配的每个模式。一旦模式匹配,则执行完匹配模式相应命令后再也不继续其余模式。若是无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。变量

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

echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read aNum
case $aNum in
    1)  echo '你选择了 1'
    ;;
    2)  echo '你选择了 2'
    ;;
    3)  echo '你选择了 3'
    ;;
    4)  echo '你选择了 4'
    ;;
    *)  echo '你没有输入 1 到 4 之间的数字'
    ;;
esac
相关文章
相关标签/搜索