Reason for ksh obsoleting -eq
The latest version of ksh obsoletes using -eq
within [[ ]]
blocks, prefering (( ))
instead. Why is this? I can’t find any documentation on the advantages of (( ))
over [[ ]]
anywhere, and I find that syntax considerably more obvious.
For example:
#!/bin/ksh
var=1
if [[ $var -eq 1 ]]
then
echo ALPHA
fi
gives
[adam@hendrix test]$ ksh -n test.sh
test.sh: warning: line 3: -eq within [[...]] obsolete, use ((...))
If you do
$ ksh -n 'if [[ 1 -eq 1 ]]; then echo hi; fi'
you get the message
ksh: warning: line 1: -eq within [[...]] obsolete, use ((...))
as you’ve seen. Now try this:
$ ksh -n 'if (( 1 -eq 1 )); then echo hi; fi'
ksh: 1 -eq 1 : arithmetic syntax error
This works:
$ ksh -n 'if (( 1 == 1 )); then echo hi; fi'
Remember that the first message is only a warning. You can continue to use that form. I doubt that it will be removed since it would break too many existing scripts. By the way, this is accepted without a warning:
$ ksh -n 'if [ 1 -eq 1 ]; then echo hi; fi'
One of the main reasons that double parentheses is preferred is that the comparison operators are the more familiar <
, <=
, ==
, etc., (at least when compared to other languages).
Double parentheses also work in Bash and zsh. A related form, arithmetic substition, works in all of them, plus it’s specified by POSIX.
$ a=$((3 * 4))
Korn, Bash and Z can also do it this way:
$ (( a = 3 * 4 ))
Even though Dash, as an example of a POSIX shell, doesn’t support double parentheses comparisons in the form if (( ... ))
, you can still do them using arithmetic substitution, but the result is the opposite from what you’d expect (this is also true for the others).
$ echo $(( 1 == 1 )); (( 1 == 1 )); echo $? # in Dash, use true instead of the second statement
1
0
$ echo $(( 1 == 2 )); (( 1 == 2 )); echo $? # in Dash, use false instead of the second statement
0
1