Bash – does bash output data instead of executing, when a script is piped

aptbashpipe

I'm running the following script on Ubuntu 14.04:

#!/bin/bash

apt-get purge -y nginx
apt-get install -y nginx

date

When I run it like cat /tmp/script | bash, apt-get starts installing, then "date" is printed (not the actual date, but the command name), then the remaining apt-get output is printed.

If however I run the script like /tmp/script, it works as expected: printing the date after apt-get finished.

Why does this happen and how can I force bash to work when being piped to the same way it does when invoked directly?

Best Answer

You'll have to close (or otherwise redirect) the standard input of the individual commands:

#!/bin/bash

apt-get purge -y nginx <&-
apt-get install -y nginx <&-

date

Otherwise subsequent line are fed to the commands.

Related Question