sudocracy
sudocracy

Reputation: 1818

Why is there a difference in behavior when the command are piped to bash versus when bash reads the file with the commands?

Consider this bash script

§ cat sample.sh 
echo "PRESS ENTER:"
read continue;
echo "DONE";

If I run it this way, the script exits after the first echo without waiting for the read:

§ cat sample.sh | bash --noprofile --norc
PRESS ENTER:

However, if I run it this way, it works as expected:

§ bash --noprofile --norc sample.sh 
PRESS ENTER:

DONE

Why the difference?

Upvotes: 0

Views: 61

Answers (2)

wjandrea
wjandrea

Reputation: 33107

If you add echo "$continue" to the end, the issue becomes obvious:

(Also I removed the semicolons since they do nothing.)

$ cat test.sh
echo "PRESS ENTER:"
read continue
echo "DONE"
echo "$continue"
$ bash test.sh
PRESS ENTER:
foo
DONE
foo
$ bash < test.sh
PRESS ENTER:
echo "DONE"

read continue is taking echo "DONE" as input since it's coming from stdin

Upvotes: 0

rtx13
rtx13

Reputation: 2610

In the first instance, the read will absorb echo "DONE"; as both the script and user input for read are coming from stdin.


$ cat sample.sh 
echo "PRESS ENTER:"
read continue;
echo "DONE";
echo "REALLY DONE ($continue)";
$ cat sample.sh | bash --noprofile --norc
PRESS ENTER:
REALLY DONE (echo "DONE";)
$ 

Upvotes: 3

Related Questions