set -ex – The most useful bash trick of the year

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.

set -ex

Ok, one thing at a time.

set -e

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 masterfind . | 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?)

What set -e does is that it exists if any of the lines fail.

set -x

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  donepg_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/bashset -exrm -f pg_all.sql pg_all.sql.gzpg_dumpall > pg_all.sqlapack pg_all.sql.gz pg_all.sqls3cmd 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.

set -ex – The most useful bash trick of the year

相关文章:

你感兴趣的文章:

标签云: