I just discovered this great site. I was reading bash tagged posts when the following question entered my mind:
This code:
var=$RANDOM
var1=$[ $var % 13 ]
echo "var1 = $var1"
var2=$( $var % 13 )
echo "var2 = $var2"
var3=$(( $var % 13 ))
echo "var3 = $var3"
var4=`expr $var % 13` # Note revised from original post by adding the expr
echo "var4 = $var4"
Produces this output:
var1 = 7
./question: line 7: 23225: command not found
var2 =
var3 = 7
var4 = 7
So only the var2 statement does not work. My question is: is it only a matter of personal choice as to which of the other three should be used or are there other considerations that should be taken into account?
(I’ve edited this question extensively after seeing replies. Hope I’m doing this the right way.)
The
$[]and$(())versions are essentially interchangeable, except that not all shells support$[], so don’t use it — use$(())instead. Also, in both of these forms, variables used in the expression will be automatically expanded, so you don’t need to use$inside them:expris actually a command which does expression evaluation — it has most of the same capabilities as the builtin expression evaluation, but without some of the niceties. For instance, you must use$to expand variables, and must escape any operators that the shell would treat as special characters (e.g.<,>,|, etc):$()is totally different — it doesn’t do arithmetic evaluation, it runs its contents as a command. In fact, it’s almost the same as backquotes (except that it is easier to read, and has much cleaner syntax, so I always use it instead of backquotes):And just to make this more complicated, let me add some more options:
So what should you use? I’d go with
var3=$(( var % 13 ))for maximum compatibility and (IMHO) clean syntax.