bash 脚本编程五 条件语句

结合前面的例子,来写一个条件表达式。如果第一个参数没有,则输出no parameter,否则输出第一个参数。

#!/bin/bash
if [ -n "$1" ]
then
    echo "1st parameter: $1"
else
    echo "no parameter"
fi
输入带参数命令:

$ ./test.sh 'this is a test'
1st parameter: this is a test

输入无参数命令:

$ ./test.sh
no parameter


先解释一下条件语句:

if [ ... ]

then

  ...

else

  ...

fi


...表示可以编写语句的地方。

必须要用fi结束整个条件语句。

注意[ ... ] 方括号要用空格和其他字符分开。


-n 是一个操作符,判断后面的参数是否长度为0,如果不为0,返回true,为0则返回false.

这篇文档介绍的还是不错的,可以参考:

http://v.youku.com/v_show/id_XNDQ5ODE3MDQw.html

其中复杂的条件表达式如下:

if condition1
then
	statement1
	statement2
	..........
elif condition2
then
	statement3
	statement4
	........    
elif condition3
then
	statement5
	statement6
	........    


fi

-n 之外,还有其他运算符可供使用:


operatorproduces true if...number of operands
-noperand non zero length1
-zoperand has zero length1
-dthere exists a directory whose name is operand1
-fthere exists a file whose name is operand1
-eqthe operands are integers and they are equal2
-neqthe opposite of -eq2
=the operands are equal (as strings)2
!=opposite of =2
-ltoperand1 is strictly less than operand2 (both operands should be integers)2
-gtoperand1 is strictly greater than operand2 (both operands should be integers)2
-geoperand1 is greater than or equal to operand2 (both operands should be integers)2
-leoperand1 is less than or equal to operand2 (both operands should be integers)2


双操作数操作符用法如下:

$r -eq 1




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值