I am trying to make the bash script silent if everything goes fine but print out all the stderr and debug info if it crashes for some reason. Below is what I have so far.
#!/usr/bin/bash
set -e
rm -f /tmp/err
trap "sleep 1 && cat /tmp/err" ERR
l() {
ts >> /tmp/err
}
echo "About to download stuff:" > >(l)
# curl blah blah 2> >(l)
# something goes wrong in the script
invalid_cmd
It works fine only if I have the 'sleep 1' which I don't like.
Without sleep:
❯ ./demo2.sh
./demo2.sh: line 18: invalid_cmd: command not found
With sleep:
❯ ./demo2.sh
./demo2.sh: line 18: invalid_cmd: command not found
Feb 25 15:20:44 About to download stuff:
I think that is because the process substitution runs in the background and may not complete. I also don't want to blindly wait for all background tasks. Is there a better way to fix this?
waitfor all background tasks,wait, thenwaitfor the ones you care about: Capture the PID of a backgrounded task from$!with e. g.mypid="$!", and then laterwait "${mypid}".