views:

33

answers:

2

Hi,

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

cat infile | read var1; echo $var1;

same result.

why does this happen?

+1  A: 

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
Ignacio Vazquez-Abrams
A: 

Or try this:

cat file | ( read var1; echo $var1; )
Pointy
well, I tried this, and it works too. I what to know why.
Here Be Wolves