1

I'm new to linux and trying to understand in what case we place $ before variables in shell, and when we don't.

myVar=5
echo $myVar            # use $
myVar=$((myVar+1))     # why not myVar = ($myVar+1)
export myVar           # don't use $ ?
unset myVar            # don't use $ ?

It's seems kind of inconsistent. Do you know some general rule, where we place $ before the variable, and when we don't?

igor Smirnov
  • 188
  • 2
  • 8
  • 1
    Possible duplicate of [What are the special dollar sign shell variables?](https://stackoverflow.com/q/5163144/608639), [What does it mean in shell when we put a command inside dollar sign and parentheses: $(command)](https://stackoverflow.com/q/17984958/608639), etc. – jww Dec 26 '18 at 11:03
  • Basically: If you want to assign content to a variable, use `variable`. If you want to access its content, use `$variable`. – Cyrus Dec 26 '18 at 12:05
  • 2
    the question is not about special shell variables – Nahuel Fouilleul Dec 26 '18 at 13:41

2 Answers2

3

Principle:

  • Use varName if you want the variable itself (export, unset)

    • Special case: Arithmetic expansion ((expr)) and $((expr)) accepts variables that contain numeric values
  • Use $varName if you want the value or content that the variable holds (if, for, case $var in)

iBug
  • 35,554
  • 7
  • 89
  • 134
1

$ is used to expand a variable with its value, in an arithmetic expression the $ is implicit because a word will be coerced to an integer value.

myVar=$((myVar+1))
# could also be written
myVar=$(($myVar+1))
# or
((myVar=$myVar+1))
((myVar=myVar+1))
((myVar+=1))
((++myVar))
# because variable assignment can be done in an arithmetic expression

export and unset are builtins but as expansion is performed before call, they can't be called like unset $myVar because myVar would be changed to its value.

For more details Bash manual, particularly the basic features, shell expansion, shell parameter expansion.

Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36