thnkwthprtls
thnkwthprtls

Reputation: 3487

Bash - When to use '$' in front of variables?

I'm very new to bash scripting, and as I've been searching for information online I've found a lot of seemingly contradictory advice. The thing I'm most confused about is the $ in front of variable names. My main question is, when is and isn't it appropriate to use that syntax? Thanks!

Upvotes: 7

Views: 3532

Answers (2)

fedorqui
fedorqui

Reputation: 289455

Basically, it is used when referring to the variable, but not when defining it.

When you define a variable you do not use it:

value=233

You have to use them when you call the variable:

echo "$value"

There are some exceptions to this basic rule. For example in math expresions, as etarion comments.


one more question: if I declare an array my_array and iterate through it with a counter i, would the call to that have to be $my_array[$i]?

See the example:

$ myarray=("one" "two" "three")
$ echo ${myarray[1]}     #note that the first index is 0
two

To iterate through it, this code makes it:

for item in "${myarray[@]}"
do
  echo $item
done

In our case:

$ for item in "${myarray[@]}"; do echo $item; done
one
two
three

Upvotes: 8

Quillion
Quillion

Reputation: 6476

I am no bash user that knows too much. But whenever you declare variable you would not use the $, and whenever you want to call upon that variable and use its value you would use the $ sign.

Upvotes: 1

Related Questions