Results 1 to 2 of 2
Hello,
I have a basic doubt in bash scripting.
I read that "$" symbol is used for expansion. Suppose $var appears in a statement it just substitutes the value of ...
- 04-09-2010 #1Just Joined!
- Join Date
- Mar 2010
- Posts
- 9
Bash scripting doubt
Hello,
I have a basic doubt in bash scripting.
I read that "$" symbol is used for expansion. Suppose $var appears in a statement it just substitutes the value of var in that statement.
var=My name is Bala
This is wrong. It needs double quotes as it contains spaces.
right one is
var="My name is Bala"
Suppose
var="My name is Bala"
con=$var
I thought that the second line is wrong and it should be con="$var".
But bash prints My name is Bala if echo $con is typed. How is this possible?
The line should have expanded as con=My name is Bala if just substitution is used. What am i misunderstanding in this?
Also command like var=$(ls | grep data) also works the same as var="$(ls | grep data)" even if the result has more than 1 word.
Please explain me.. Thank you..
Thanks,
Bala
- 04-09-2010 #2
I may get the subtlety of this incorrect, but essentially you have to think of the variable assignment in terms of lvalue = rvalue just as you would in any compiled language. The rvalue is a pointer to the stored value that was obtained during the language scan.
In BASH, the rvalue scan of
does not work because the first space character terminates the token scan. The remaining words are then expected to be a new command string.Code:var=My name is Bala
But the rvalue scan of
does work because the quoting allows the token scan to continue over the spaces and only complete after the second quote.Code:var="My name is Bala"
Now when BASH encounters
it is not re-scanning a textual substitution of what $var is set to, at that time it is assigning the stored value of $var that was already scanned to $con.Code:con=$var
Now if you quote a variable on the right hand side, it is subject to quoting rules. I think in the case of
what is happening is that $var is being evaluated, then substituted literally, and then scanned. The result is essentially the same, but the quoting changes the scanning behavior. Chapter 5 of the Advanced Bash Scripting Guide has more on quoting.Code:con="$var"


Reply With Quote