31 August 2014 5 comments Linux
I just learned a really good bash trick which is something I've wanted to have but didn't really appreciate that it was possible so I never even searched for it.
Ok, one thing at a time.
What this does, at the top of your bash script is that it exits as soon as any line in the bash script fails.
Suppose you have a script like this:
git pull origin master find . | grep '\.pyc$' | xargs rm ./restart_server.sh
If the first line fails you don't want the second line to execute and you don't want the third line to execute either. The naive solution is to "and" them:
git pull origin master && find . | grep '\.pyc$' | xargs rm && ./restart_server.sh
but now it's just getting silly. (and is it even working?)
set -e does is that it exits if any of the lines fail.
What this does is that it prints each command that is going to be executed with a little plus.
The output can look something like this:
+ rm -f pg_all.sql pg_all.sql.gz + pg_dumpall + apack pg_all.sql.gz pg_all.sql ++ date +%A + s3cmd put --reduced-redundancy pg_all.sql.gz s3://db-backups-peterbe/Sunday/ pg_all.sql.gz -> s3://db-backups-peterbe/Sunday/pg_all.sql.gz [part 1 of 2, 15MB] 15728640 of 15728640 100% in 0s 21.22 MB/s done pg_all.sql.gz -> s3://db-backups-peterbe/Sunday/pg_all.sql.gz [part 2 of 2, 14MB] 14729510 of 14729510 100% in 0s 21.50 MB/s done + rm pg_all.sql pg_all.sql.gz
...when the script looks like this:
#!/bin/bash set -ex rm -f pg_all.sql pg_all.sql.gz pg_dumpall > pg_all.sql apack pg_all.sql.gz pg_all.sql s3cmd put --reduced-redundancy pg_all.sql.gz s3://db-backups-peterbe/`date +%A`/ rm pg_all.sql pg_all.sql.gz
And to combine these two gems you simply put
set -ex at the top of your bash script.
Thanks @bramwelt for showing me this one.
Checkout out ExplainShell.com