I was playing with shell scripting, when a strange thing happened. I need someone to explain it.
I have a file 'infile', contents:
line one
line2
third line
last
a test script test.sh, contents:
read var1
echo $var1
i executed:
cat infile | ./test.sh
output was
line one
Then I did:
cat infile | read var1
echo $var1
Result: a blank line.
I even tried
c开发者_开发百科at infile | read var1; echo $var1;
same result.
why does this happen?
The pipe causes the command after it to run in a subshell, which means that environment variables won't be propagated to the main shell. Use redirection or a herestring to get around this:
read var1 < infile
Or try this:
cat file | ( read var1; echo $var1; )
精彩评论