Shell script test

2019-02-23 01:02发布

I'm tring to update a bash script written by someone else and I've come accross a line I'm not sure about.

Can anyone tell me what the following check does:

if [ :$RESULT != :0,0 ]

I assume it's checking for some value in $RESULT, possibly with a substring?

Any help appreciated!

3条回答
仙女界的扛把子
2楼-- · 2019-02-23 01:34

Sometimes you'll see an x used in the way that the colon is used in your example.

The preferred way to do this type of test in Bash is to use the double square bracket:

if [[ $RESULT != 0,0 ]]

The double bracket form allows more flexibility, improved readability, reduced need for escaping and quoting and a few more features. See this page for more information.

If you want to test numeric values, instead of strings or files, use the double parentheses:

if (( 3 + 4 > 6 ))
查看更多
欢心
3楼-- · 2019-02-23 01:42

I think the : is a common trick people use in case the variable is empty.

If it's empty, then the shell would have this:

if [  != 0,0 ]

which would be a syntax error. Putting the : in front means that if the variable is empty the shell has this:

if [ : != :0,0 ]

which is not a syntax error and would (correctly) report false.

查看更多
老娘就宠你
4楼-- · 2019-02-23 01:47

The command [ is just an alias of the command test, the closing square bracket just being sytax sugar (the command [ ignores the last argument if it's a closing bracket), so the line actually reads

if test :$RESULT != :0,0

It compares if the string :$RESULT equals to the string :0,0. The colon is prepended for the case that the variable $RESULT is empty. The line would look like the following if the colon was omitted and $RESULT was an empty string:

if test  != 0,0

This would lead to an error, since test expects an argument before !=. An alternative would be to use quotes to indicate that there is an argument, which is an empty string:

if test "$RESULT" != 0,0
# Will become
if test "" != 0,0

The variation you posted is more portable, though.

查看更多
登录 后发表回答