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和不同的选项来测试文件的许多特性如下表

[img]http://dl.iteye.com/upload/attachment/0075/8121/2cc18826-fc4a-34d9-aa9c-d6e3521de2e0.png[/img]

[]与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表明程序正常运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值