Find the answer to your Linux question:
Results 1 to 4 of 4
I'm confused why this assignment works: Code: echo 'store this' | while read val1 do echo "$val1" done but this doesn't: Code: echo 'store this too' | read val2 echo ...
  1. #1
    Ezo
    Ezo is offline
    Just Joined!
    Join Date
    Dec 2007
    Posts
    10

    Smile Elementary question on script variable assignment

    I'm confused why this assignment works:

    Code:
    echo 'store this' | while read val1
    do
    echo "$val1"
    done
    but this doesn't:

    Code:
    echo 'store this too' | read val2
    
    echo "$val2"
    I can assign the value with this:

    Code:
    val3=$(echo 'store this aswell') > /dev/null
    
    echo "$val3"
    but it seems too longwinded.

    What's the best method for storing a string from a script statement?

    Many thanks.

  2. #2
    Linux Guru anomie's Avatar
    Join Date
    Mar 2005
    Location
    Texas
    Posts
    1,692
    If all you're doing is assigning a literal string to a variable, how about:

    $ VAL1='Store This'

    If you need to store the value of some operation, this is pretty standard - e.g.:

    $ VAL2=$( hostname )
    Last edited by devils casper; 12-20-2007 at 06:10 PM. Reason: posts merged.

  3. #3
    Ezo
    Ezo is offline
    Just Joined!
    Join Date
    Dec 2007
    Posts
    10
    Righty I'll stick with that method then.

    Thanks

  4. #4
    scm
    scm is offline
    Linux Engineer
    Join Date
    Feb 2005
    Posts
    1,044
    Quote Originally Posted by Ezo View Post
    I'm confused why this assignment works:
    Code:
    echo 'store this' | while read val1
    do
    echo "$val1"
    done
    but this doesn't:
    Code:
    echo 'store this too' | read val2
    echo "$val2"
    The reason the second example doesn't work is because when you use a pipe, the command is executed in a subshell, so the parent process can't see the assigned variable. The first example doesn't really work, either, and if you echo the variable after the "done" you'd realise this. Of course, this is the behaviour of bash, both examples work perfectly in a decent shell like ksh.

Posting Permissions

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