Bash – Prevent sudo, apt-get, etc. from swallowing pasted input to STDIN

bashscriptingstdinsudo

I often write up wiki instructions to install various server packages on Ubuntu (11.10 Oneiric at the moment). They always involve things like:

sudo apt-get install -y postfix
sudo cp ~/siteconfig/etc/postfix/main.cf /etc/postfix

but when you cut and paste this to a terminal, either sudo, apt-get, or some subshell randomly swallows the subsequent lines of input, and only the apt-get install happens.

Is there a way to make this more cut-and-paste-friendly? I suppose I could wrap each section with

cat > script <<EOF
apt-get install -y postfix
cp ~/siteconfig/etc/postfix/main.cf /etc/postfix
EOF
sudo sh ./script

but is there a better way?

Best Answer

A way to both avoid the cut-and-paste problem, as well as safely run the commands in succession is to put them on the same line separated by && which will only execute the cp on the successful completion of the sudo apt-get install:

sudo apt-get install -y postfix && sudo cp ~/siteconfig/etc/postfix/main.cf /etc/postfix

Afterall, if the first command fails you probably don't want to continue executing the rest of the commands.

As for why the commands get swallowed when you paste multiple lines at once... when postfix gets installed it asks configuration questions with the debconf dialog frontend which is likely what's interfering with the cut-and-paste. Maybe a different front-end like readline or noninteractive would interfere less? Still, I would use the && method anyway since it is safer.

If you're installing postfix with your scripts it sounds like maybe you're trying to automate the install of new systems? If so, consider using preseeding as an option (here is some Ubuntu 11.10 specific documentation) or maybe use puppet?

Related Topic