7

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!

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, 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]?
That is not entirely correct. For example, in math context you don't use it when refering to the variable - x = 2; y = 1; let z=++x*++y; echo $z
Change echo $value to echo "$value"
@fedorqui Thanks, I'm still a little unsure how to do this within a loop though. It seems like getting a static location's fairly simple, but if I have an iterator i declared, how do I get the ith spot?
@thnkwthprtls I just updated again showing how to iterate through an array. Hope it helps.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.