在Unix中,程序结束时会返回一个状态,这个状态可以指示程序是否成功执行。如果使用了pipeline,那么返回的是最后一个程序的状态。
我们可以使用$?变量来获取上一个程序的状态。例如
$ echo $?
0
有了这个,我们就可以使用if语句来控制程序的流程了,如
if who | grep "$user"
then
echo "$user is logged on"
fi
这个程序根据传入的参数来判断用户是否登录。这里直接使用程序的返回值来当判断条件,我们也可以使用test命令来作为if的条件,test命令回去执行传入的表达式,返回结果。如test "$name" = julio ;test命令的变量和运算符之间需要空格隔开,这点和变量赋值相反。
test命令的替代形式是使用中括号,注意中括号前后要有一个空格。如
if [ "$name" = julio ]
then
echo "Would you like to play a game?"
fi
[ ]命令提供了一些对整数操作的方法,如下
int1 is equal to int2.
int1 is greater than or equal to int2.
int1 is greater than int2.
int1 is less than or equal to int2.
int1 is less than int2.
int1 is not equal to int2.
对文件操作的方法
file is a directory.
file exists.
file is an ordinary file.
file is readable by the process.
file has nonzero length.
file is writable by the process.
file is executable.
file is a symbolic link.
我们可以在这些操作符前加上一些逻辑操作符来对结果进行逻辑操作,如
!用来对结果取反,[ ! -f "$mailfile" ]
-a 逻辑与,只有当所有结果为真时才返回0,-a的优先级比整数操作符,字符操作符和文件操作符的优先级低,[ -f "$mailfile" -a -r "$mailfile" ]-o 逻辑或,只要有一个的结果返回真,就返回0,-o的优先级比-a低,[ -n "$mailopt" -o -r $HOME/mailfile ]
if-else if-else语句结构
if commandl
then
command
command
...
elif command2
then
command
command
...
elif commandn
then
command
command
...
else
command
command
...
ficase语句结构
case value in
pat1) command
command
...
command;;
pat2) command
command
...
command;;
...
patn) command
command
...
command;;
esac: 命令表示什么都不做,例如
if grep "^$system" /users/steve/mail/systems > /dev/null
then
:
else
echo "$system is not a valid system"
exit 1
fi&&,这个可以用来实现类似if的功能,command1
&& command2,只有当command1返回0时,command2才能执行||,这个和 &&类似,command1 || command2,只有command1返回非零值时,command2才能执行。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7899089/viewspace-628034/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/7899089/viewspace-628034/