UNIX and Linux Shell Script Test Command

UNIX and Linux Shell Script Test Command

The Test command is often used in control flows. It returns 0 if something is true, and non-zero if it is false. Statements such as the "if" command are a great place to make use of this.

Common Test Cases

test returns true in the following cases:
test ss is not a null string
test -n stringstring is nonzero
test sting1 = string2the two strings are equal
test sting1 != string2the two strings are not equal
test integer1 -eq integer2the integers are equal
test integer1 -ge integer2integer1 is greater or equal to integer2
test integer1 -gt integer2integer1 is greater than integer2
test integer1 -le integer2integer1 is less than or equal to integer2
test integer1 -lt integer2integer1 less than integer2
test integer1 -ne integer2integer1 is not equal to integer2
test -f fileif the file exists and is not a directory
test -r filethe file is readable
test -w filethe file is writable
test -d dirdir is a directory

An Example of Test

Here, we simply check to see if java exists in /usr/bin using the "test" command.


if test -f /usr/bin/java
then
	echo "Java exists in /usr/bin/"
fi

Using Square brackets

Square brackets can be used to replace the test command in most command shells. Here is an example of this. Note that the spaces between the brackets and the test operation are vital here.


if [ -f /usr/bin/java ]
then
	echo "Java exists in /usr/bin/"
fi

Testing strings

When testing strings in shell scripts be aware that a null string may cause the shell interpreter to error.

For example:
[ string1 == string2 ]
will be fine as long as neither string is null, but if one or both evaluate to null, then the shell command interpreter will throw an error. Put quotes around your string to avoid this error condition:
[ "string1" == "string2" ]

Using Double Square brackets

With some shell command interpreters such as the Korn Shell and Bash you can also use double square brackets. The test operators used for single brackets are the most standard, whereas the double square bracket test operators behave in a slightly different way.

For example:
[[ string1 == string2 ]]
is valid in in Korn shell, and checks to see if the value of string1 equals string2. 

If you were to write this using single brackets:

[ string1 == string2 ]This is wrong and some command shells would complain
[ string1 = string2 ]Better. This would work unless one string was null
[ "string1" = "string2" ]Even better! This should work with all Bourne derived command shells
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值