shell程序设计之if...then

控制结构
if ... then、for...in、while、until以及case,此外,还配合break和continue调整shell脚本中的命令执行顺序。

if...then语法:
if test-command
    then
        commands
fi

test内置命令,if语句测试test-command返回的状态,并基于这个状态转移控制。示例如下:
#!/bin/bash

echo -n "word1:"
read word1
echo -n "word2:"
read word2

if test "$word1" == "$word2"
        then
                echo "Match"
fi
echo "End of prog."



检查参数示例:
下面的脚本的开头使用if结构去检查命令行是否至少提供一个参数,-eq比较两个整数,特殊变量$#表示命令参数个数。
#!/bin/bash

if test $# -eq 0
        then
                echo "you must supply at least one argument."
                exit 1
fi
echo "Program running."



可使用test和不同的选项来测试文件的许多特性如下表

shell程序设计之if...then

[]与test同义,使用[]代替test,可以把test的参数用方括号括起来,代替关键字test。括号两边必须有空白符(空格或TAB符)

if...then...else
if test-command
    then
        commands
    else
        commands
fi

if test-command ; then
        commands
    else
        commands
fi

if...then...elif
if test-command
    then
        commands
    elif test-command
        then
            commands
    else
        commands
fi

exit 1表明程序的执行遇到了一个错误;
exit 0表明程序正常运行。



你可能感兴趣的:(shell)