oliv oliv - 6 days ago 5
Bash Question

How to use variables in bash conditional expression?

I'd like to have some explanation on how to best use variables in bash conditional expressions

[[...]]
.

I usually write
if
statement in this way:

var=1;
# some code...
if [[ $var -eq 1 ]]; then echo "ok"; else echo "fail"; fi


and this return
ok
as I expected.

Now I saw in some script the same similar statement like:

var=1;
# some code...
if [[ var -eq 1 ]]; then echo "ok"; else echo "fail"; fi


The only difference is the missing parameter expansion character
$
in the conditional expression
[[...]]
.

I actually expected this statement to give an error, but this syntax is accepted and returns the
ok
string.

I tested this statement using
bash
(GNU bash, version 4.3.46),
zsh
(5.1.1),
ksh
(93u+ 2012-08-01) and busybox
ash
(BusyBox v1.23.2).

I only get an error with busybox shell:

ash: var: bad number


I saw in the
bash
man page, in the
ARITHMETIC EVALUATION
paragraph, that:


Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax


But I didn't find anything special related to parameter expansion in the
CONDITIONAL EXPRESSIONS
paragraph.

So, should conditional expression contain
$
when referring to variable or not? and why?

Answer

The trigger here is -eq; since it is defined to perform integer comparison, its operands are evaluated in an arithmetic context. This isn't explicitly documented, though.

You should use the $, though. [[ is an extension, so there is no guarantee that it will behave identically in every shell that defines such a construct. In fact, I wouldn't even assume that [[ var -eq 3 ]] will continue to behave this way in future versions of the same shell. (( var == 3 )) is, though, documented to perform expansion of var since you are in a explicit arithmetic context.