Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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!

like image 961
thnkwthprtls Avatar asked Sep 06 '13 12:09

thnkwthprtls


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

When should I wrap quotes around a shell variable?

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape).

What does $? Signify in bash?

$? - It gives the value stored in the variable "?". Some similar special parameters in BASH are 1,2,*,# ( Normally seen in echo command as $1 ,$2 , $* , $# , etc., ) .

What is the use of $? Sign in shell script?

$? determines the exit status of the executed command. $ followed by numbers (e.g. $1 , $2 , etc.) represents the parameters in the shell script.


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
like image 198
fedorqui 'SO stop harming' Avatar answered Oct 12 '22 23:10

fedorqui 'SO stop harming'


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.

like image 33
Quillion Avatar answered Oct 12 '22 23:10

Quillion