Bash: download and execute shell scripts

Sometimes, when running 1 bash script repeatedly on several different machines, I found that being able to download and immediately execute a script is very handy.

The following command will download a script and immediately execute it:

bash <(curl -s http://geeklab.info/my-script.sh)

This command uses Bash's Process Substitution to do it's job. command2 <(command) means for bash to put the output of command in a pipe and then run command2 [tempfile]. So above statement does the same as:

TMPFILE=$(mktemp /tmp/my.XXXXX)
curl -s http://geeklab.info/my-script.sh > $TMPFILE
bash $TMPFILE
rm $TMPFILE

Process substitution is also very useful when you want to know the difference between the output of two commands:

diff <( command1 ) <( command2 )

Furthermore, it's possible to pipe the contents of the temporary file into command2. For instance:
bash < <(curl http://geeklab.info/my-script.sh) would do the same as:

TMPFILE=$(mktemp /tmp/my.XXXXX)
curl -s http://geeklab.info/my-script.sh > $TMPFILE
bash < $TMPFILE
rm $TMPFILE

With bash, this difference is small, but with other commands, it may not be.

© GeekLabInfo Bash: download and execute shell scripts is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Leave a Reply