Thursday, February 10, 2011

do or die()

Apparently today is my day to learn Bash tidbits (see prev posts). I've always been fond of concise ways to script do x or die with an informative message. Eg PHPs something() or die("even though I can enter a helpful message I won't damnit");.

So how do we do this in Bash? Well this type of thing pops up fairly regularly:
if [ "$?" -ne "0" ]; then 
  echo $cmd " failed :("
  exit 1; 
You can use A || B to chain things on failure (if A succeeds B doesn't execute) ... so why don't people do this:
mycommandthatmightfail || (echo "informativeness!"; exit 1)
Note that as we used ; to separate the commands to run if mycommandthatmightfail does indeed fail they will all run even if some of them fail.

No comments:

Post a Comment