第二种:if ... else ... fi,具体如下:
if [ expression ]
then
statement(s) to be sxecuted if expression is true
else
statement(s) to be sxecuted if expression is not true
fi
一个简单的实例
cat ifparam.sh
#!/bin/sh
if [ $# -lt 3 ]; then
echo "Usage:`basename $0` arg1 arg2 arg3" >&2
exit 1
fi
#EOF
echo "arg1:$1"
echo "arg1:$2"
echo "arg1:$3"
脚本注解:
1.$#表示参数输入的个数
2.basename $0打印文件的名称
3.若输入小于三个参数则,将输出一个信息,这个信息被当做是错误信息(>&2)。
执行脚本:
sh ifparam.sh scott tom
Usage:ifparam.sh arg1 arg2 arg3
sh ifparam.sh scott tom jim
arg1:scott
arg1:tom
arg1:jim
再来看一个测试:
cat ifeditor.sh
#!/bin/csh
#if [ -z $EDITOR ]①
#if [ -z "`echo $EDITOR`" ]③
#下面这种写法不能正确的计算出环境的值
#因为wc -c计算包括新的空的行
#if [ `echo $EDITOR | wc -c` -eq 0 ]②
if [ -z "`echo $EDITOR`" ]
then
echo "Your EDITOR environment is not set"
else
echo "Using $EDITOR as the default editor"
fi
#EOF
sh ifeditor.sh
Your EDITOR environment is not set
这里使用三种方式去检测环境变量是否设置;
①直接报错:语法错误
②正确写法,使用test检测,-z表示如果为设置则长度为0返回值为true
③wc -c计算包括了空行,所以不准确
