How to obtain last bash error

stanleyxu2005 asked:

I am working with a terrible project. It uses a lot of messy shell script in background. Script might include some other scripts. And many error outputs were redirected to /dev/null. When a script is not executed successfully, I can use echo $? to see the error code, but I am not able to know what command returned this error code.

These scripts are there. I do not want to review all code and add extra code to handle errors in a gentle way. Now I have two questions here:

  1. Is it possible to print the last bash command with arguments, that was not executed successfully?
  2. How to live with such messy shell script code?

My answer:


Try

bash -x /my/script

to print every line of the script as it is executed.

Can’t run the script like this? You can also add it to the shebang at the first line of the file.

#!/usr/bin/bash -x

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.