korn shell script puzzler

Here is a very simple Korn shell script running on an AIX 5.3 box.

Why does this work without the $ prepended to RET_CD?

#!/bin/ksh
RET_CD=0
if [ RET_CD -ne 0 ] && [ RET_CD -ne 2 ] 
then
  echo "RET_CD is not 0 and not 2"
else
  echo "RET_CD is a 0 or a 2" 
fi

In Korn shell conditional expressions are evaluated in double brackets ( [[..]] ). Integer variables do not need $ signs in these. The test command (or its synonym [..] ) is also supported as an external command, but ksh also has a built-in that is used instead of this external test command to speed up execution.

My guess is that this built-in is using some or all of the code of the double bracket version and in the process also evaluates integer variables without the $-signs. It is still compliant because it evaluates integer variables with $-signs correctly.

If you want your code to be compatible with other shells, it is best to use $-signs with integer variables anyway if you are using single brackets.

Scrutinizer,

I thank you for the reponse.

:slight_smile:

Interesting post.

This variation of old Bourne works by design for compatibility with old shells.

#!/bin/ksh
RET_CD=0
if [[ RET_CD -ne 0 && RET_CD -ne 2 ]]
then
  echo "RET_CD is not 0 and not 2"
else
  echo "RET_CD is a 0 or a 2"
fi

./scriptname
RET_CD is a 0 or a 2

As Scrutinizer advises, stick to the modern syntax with the $ prefix.