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 ...
- 12-20-2007 #1Just Joined!
- Join Date
- Dec 2007
- Posts
- 10
Elementary question on script variable assignment
I'm confused why this assignment works:
but this doesn't:Code:echo 'store this' | while read val1 do echo "$val1" done
I can assign the value with this:Code:echo 'store this too' | read val2 echo "$val2"
but it seems too longwinded.Code:val3=$(echo 'store this aswell') > /dev/null echo "$val3"
What's the best method for storing a string from a script statement?
Many thanks.
- 12-20-2007 #2
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 )
- 12-20-2007 #3Just Joined!
- Join Date
- Dec 2007
- Posts
- 10
Righty I'll stick with that method then.
Thanks
- 12-22-2007 #4Linux Engineer
- Join Date
- Feb 2005
- Posts
- 1,044
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.


Reply With Quote
