Are these bash statements equivalent?

I just opened this wonderful site. I was reading bash posts with tags when the following question entered my head:

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 conclusion:

var1 = 7
./question: line 7: 23225: command not found
var2 = 
var3 = 7
var4 = 7

So only the var2 instruction does not work. My question is this: is there only a personal choice, which of the other three should be used, or are there other considerations that should be considered?

(I edited this question in detail after looking at the answers. Hope I'm doing it right.)

+3
source share
4 answers

$[] $(()) , , $[], - $(()). , , , , $ :

var=$RANDOM
echo $var             # prints 7482 (in my example run)
echo $[ $var % 13 ]   # prints 7
echo $[ var % 13 ]    # prints 7
echo $(( $var % 13 )) # prints 7
echo $(( var % 13 ))  # prints 7

expr , - ​​ , , . , $ , (, <, >, | ..):

expr $var % 13        # prints 7
echo `expr $var % 13` # prints 7, just by a less direct route

$() - , . , , backquotes ( , , backquotes):

echo $(expr $var % 13) # prints 7, same as with backquotes

, :

(( var5 = var % 13 )) # This is an arithmetic statement (that happens to contain an assignment)
echo $var5            # prints 7
let "var6 = var % 13" # Another form for pretty much the same thing
echo $var6            # prints 7

declare -i var7  # declare var7 as an integer...
var7="var % 13"  #  to force values assigned to it to be evaluated
echo $var7       # prints 7

, ? var3=$(( var % 13 )) (IMHO) .

+4

$[…] $((…)) . $[…] bash zsh; $((…)) .

expr , expr. , , , expr. expr.

$( $var % 13 ) , $var (, , ) .

+2

var=$( $var % 13 )

, $(( var % 13 ))

var=$(( $var % 13 ))

var=$var % 13

: , $(( var % 13 )) $var 13.

, var1 var3 . expr - , bash .

+1
((var%=13))

- : var = ((var% 13))

+1

All Articles