Sometimes I need to maintain programs that invoke shell scripts which invokes other programs and scripts. Therefore, when the main shell script ends with exit code 126, it is a struggle to find out which of the invoked scripts and commands set that exit code.
Is there a way to see which command was the reason for the exit code to make it easier to check for its permissions?
Best Answer
If on Linux, you could run the command under
strace -fe process
to know which process did anexit_group(126)
and what command it (or any of its parent if it didn't execute anything itself) executed last before doing that:Above, that was process 26326 that first exited with 126, that was because it attempted to execute
/
. It was a child of process 26325 that last executedsh -c /
.If those scripts are
bash
scripts or if they aresh
scripts andsh
happens to bebash
on your system, you could do:That doesn't tell us exactly what process exited with 126 but could give you enough clue.
We use
BASH_TRACEFD=7 7>&2
so that the traces are output on the original stderr, even when stderr is redirected within the scripts. Otherwise those trace messages could affect the behaviour of the scripts if they do things like(....) 2>&1 | ...
. That assumes those scripts don't explicitly use or close fd 7 themselves (that's would be unlikely, a lot more unlikely than them redirecting stderr).