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 |
Regards var="My name is Bala", That works, so would var='My name is Bala'. Everything is single quotes is taken completely verbatim whereas expansion is done in double quotes. When bash finds something in single or double quotes it expands it to a single word.
Bash expands whatever is to the right of an assignment "=" as a single word. The GNU Bash Reference says "name=[value] ... All values undergo tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal ... Word splitting is not performed" |
Just to clarify for you further, var=$(ls | grep data) works because the expression is expanded, and var="$(ls | grep data)" works because it was treated as a single word, and then expanded. This expression var='$(ls | grep data)' would not work. The text inside the single quotes is not expanded and instead is taken as is. So $var would hold the text $(ls | grep data).
|
Perhaps another point that is confusing you is that when a variable appears on the right and is expanded, it is treated as if you had placed quotes around it. That is why con=$var works, and var=My name is Bala doesn't.
|
The key point is how the thing is parsed.
When you do this: Code:
var=value with spaces Code:
var=value command parameters Code:
DISPLAY=:0.1 gvim ~/.conkyrc Code:
$ var=":0.1 gvim ~/.conkyrc" |
All times are GMT -5. The time now is 08:18 AM. |