Reputation: 611
I'm recently learning bash and confused when a variable would add $
. I find code like:
i=1
while [ $i -le 10 ]
do
echo "$n * $i = `expr $i \* $n`"
i=`expr $i + 1`
done
Upvotes: 0
Views: 75
Reputation: 532313
A key thing to remember is that variables are never passed around in shell, only values. When you call something like
echo "$foo"
you might think that echo
receives $foo
, then looks at its value. Instead, the shell first expands $foo
to the value of foo
, then passes that value to echo
.
The dollar sign is used to introduce any such parameter expansion, where the value of a parameter is needed. Consider:
$ foo=10
$ echo foo
foo
$ echo $foo
10
From the perspective of the echo
command, there is no difference between echo $foo
and echo 10
; in both cases, the value passed to echo
is 10.
Upvotes: 2
Reputation: 21965
I thought @slaks' [ answer ] wouldn't be complete without this :
When not to add $
for a variable
With The Double-Parentheses [ Construct ]
x=5;
(( x++ )) # fine, note this construct accept $x form too.
When using export
var=stuff
export var #fine
When using declare
declare -a arry # fine
When not omit $
As @rici pointed out in the comment below:
you can leave out the $ in any arithmetic context, not just ((...)) and $((...)) ... For example, if arr is an array (not associative), then ${arr[x++]} is also fine.
Consider
# You wanted to create an associative array 'test' but you forgot to do
# declare -A test , Now below
test[foo]=bar # is foo a variable or a key, the reader isn't clear
# creates a simple array
echo ${test[foo]} # is foo a variable or a key?
bar
declare -p test
declare -a test='([0]="bar")'
# What happened?
# Since foo was not set at the point when 'test[foo]=bar' was called,
# bash substituted it with zero
# I meant to say test[foo]=bar hides an error.
Upvotes: 3
Reputation: 888185
The $
substitutes the variable. Writing $i
will insert the value of i
, no matter where you write it.
If you want to assign to the variable, that obviously makes no sense.
Upvotes: 4
Reputation: 61
To set a value to a variable in bash you can do a=10 Where as to access the value of that variable you need to use echo $a which mean $ is a symbol used to access the value of a variable.
i=1 ---> setting variable as 1
while [ $i -le 10 ] ---> simple while statement which loops till value of i is less that 10
do
echo "$n * $i = `expr $i \* $n`" ---> This is a syntax error bcoz value of n is never assigned
i=`expr $i + 1` ---> This line add's one to value of i
done ---> terminate while loop
Hope that explains you.
Upvotes: 0