0

I'm struggling to understand how to use bash's trap command correctly.

I have a script where I want to

  1. Do A
  2. Do B, which might fail
  3. Whether B succeeded or failed, do C
  4. If B failed, also do D

I think I get how to do 1-3. That'd look something like;

echo "I am A"

function B {
   echo "I am C"
}
trap B EXIT

echo "I am B"

But where do I put D? If it goes inside function B, it executes whether or not B fails. If it's outside, it only happens on success. Am I using trap wrong?

Alex
  • 2,555
  • 6
  • 30
  • 48

1 Answers1

1

Traps can use arbitrary code blocks instead of just function names.

You could make the call to the function in the trap evaluate success or failure and call the next function when required.

trap 'B || D' exit

You could allso make the whole B || D the body of an E and just call that on exit, if you prefer to stick to using function names. ;)

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36