Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When is it optional to use ‘$’ character before a variable name in bash?

Could someone please explain why this works, specifically the fact that I am not using ‘$’ character before the names of the variables inside the if statement? I have searched the Bash Reference Manual, but could not find an explanation.

#!/usr/bin/env bash

one="$1"
two="$2"
three="$3"
four="$4"

if [[ one -le two ]] && [[ three -ge four ]]; then
        echo "TRUE:  $one <= $two && $three >= $four"
else
        echo "FALSE: $one <= $two && $three >= $four"
fi

I have also tested it with for x1 in {1..3}; do for x2 in {1..3}; do for x3 in {1..3}; do for x4 in {1..3}; do ./test $x1 $x2 $x3 $x4; done; done; done; done |sort and it works perfectly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the description of Bash Conditional Expressions the description of the arithmetic comparison operators (-lt, -gt, etc.) says:

When used with the [[ command, Arg1 and Arg2 are evaluated as arithmetic expressions (see Shell Arithmetic).

And when you follow that link it says:

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

And the description of Arithmetic Expansion$((expression)) says:

All tokens in the expression undergo parameter and variable expansion, command substitution, and quote removal. … The evaluation is performed according to the rules listed below (see Shell Arithmetic).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading