Find the answer to your Linux question:
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 ...
  1. #1
    Just 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

  2. #2
    Just Joined! sixdrift's Avatar
    Join Date
    Jan 2007
    Location
    In and around and about Cary, NC
    Posts
    44
    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

    Code:
    var=My name is Bala
    does not work because the first space character terminates the token scan. The remaining words are then expected to be a new command string.

    But the rvalue scan of

    Code:
    var="My name is Bala"
    does work because the quoting allows the token scan to continue over the spaces and only complete after the second quote.

    Now when BASH encounters

    Code:
    con=$var
    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.

    Now if you quote a variable on the right hand side, it is subject to quoting rules. I think in the case of

    Code:
    con="$var"
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...