开发者

test command in KornShell (ksh)

开发者 https://www.devze.com 2023-01-22 09:25 出处:网络
I have a question on the test command in the KornShell (ksh). I know -ne is for comparing integers and!= is for comparing strings. How will the test command behave if one argument is a string and the

I have a question on the test command in the KornShell (ksh). I know -ne is for comparing integers and != is for comparing strings. How will the test command behave if one argument is a string and the other is an integer? I have below conditions in my code and b开发者_Python百科oth are working properly.

Code:

myCount=1
myCount=`expr $myCount+ 0`
temp=`ps -aef | grep damn | wc -l`
if [ $temp -ne $myCount]; then
        echo ERROR Number
fi

if [ $temp != $myCount ]; then
        echo ERROR Strings
fi

Output:

ERROR Number
ERROR Strings


The type is not relevant because it's a simple text substitution. In other words, the value of the variable $temp will be substituted in place of $temp (for example).

At least for the version of ksh I'm running, for the numeric comparison, if the value starts with a non-numeric, it will equate to 0. If it starts with a numeric but contains non-numerics, you will get an error.

For example:

$ export s1=xyz
$ export s2=7xyz
$ export i1=0
$ if [ $i1 -eq $s1 ]
> then
>     echo equal
> fi
equal
$ if [ $i1 -eq $s2 ]
> then
>     echo equal
> fi
ksh: 7xyz: bad number `7xyz'

However, based on your comments, that may not be the case for all versions of ksh.

Based on that, I would try to ensure that you use string comparisons for strings and numeric comparisons for numbers. Anything else may be non-portable.


But your code is flawed anyway.

temp=ps -aef | grep damn | wc -l will always return at least 1, since it will find the grep command as well as being a string padded with leading spaces, which is why both of your tests are true.

Piping to wc is also unnecessary since the -c switch of grep will count for you.

better code would be:

temp=ps -aef |grep damn |grep -cv grep which will return the number of running instances of processes containing the damn string and it will be a number.


Using ksh93 and GNU coreutils expr 7.4 your command:

myCount=`expr $myCount+ 0`

gives me a syntax error and sets myCount to null which causes both if statements to output "ksh: [: argument expected" errors. Try putting a space before the plus sign. Also, there needs to be a space before ].

You shouldn't need to convert myCount or temp to integers. The coercion of myCount using expr is completely unnecessary.

I prefer this form for comparing integers since it allows you to use symbolic comparison operators such as != and > instead of -ne and -gt:

if (( $temp != $myCount ))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号