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
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
5 Comments
thnkwthprtls
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]?
etarion
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 $zAleks-Daniel Jakimenko-A.
Change
echo $value to echo "$value"thnkwthprtls
@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?
fedorqui
@thnkwthprtls I just updated again showing how to iterate through an array. Hope it helps.