Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I'm writing a shell script that needs to do a bunch of commands and every command depends on every previous command. If any command fails the entire script should fail and I call an exit function. I could check the exit code of each command but I am wondering if there is mode I can enable or a way to get bash to do that automatically.

For example, take these commands:

cd foo || myfunc
rm a || myfunc
cd bar || myfunc
rm b || myfunc


Is there a way where I can somehow signal to the shell before executing these commands that it should call myfunc if any of them fail, so that instead I can write something cleaner like:

cd foo
rm a
cd bar
rm b
share|improve this question

2 Answers 2

up vote 5 down vote accepted

You can use bash trap ERR to make your script quit if any command returns status greater than zero and execute your function on exiting.

Something like:

myfunc() {
  echo 'Error raised. Exiting!'
}

trap 'myfunc' ERR

# file does not exist, causing error
ls asd
echo 123

Note that bash trap ERR does implicit set -o errexit or set -e and is not POSIX.

And the ERR trap is not executed if the failed command is part of the command list immediately following until or while keyword, part of the test following the if or elif reserved words, part of a command executed in && or || list, or if the command’s return status is being inverted using !.

share|improve this answer
    
Thank you, that works. –  test Dec 11 '14 at 6:10

This can be accomplished easily with a while-loop:

#!/bin/bash

while [ ! stderr ]; do
  cd foo
  rm a
  cd bar
  rm b
done
myfunc
share|improve this answer
    
Interesting. What if the command doesn't output to stderr? –  test Dec 11 '14 at 17:47
    
@test The exclamation mark means 'while not', so in this example if there is no error it will do everything in order then run myfunc, or if it reaches an error it will beak out of the loop and run myfunc. –  cremefraiche Dec 11 '14 at 17:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.