2

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?
stanleyxu2005
  • 179
  • 1
  • 1
  • 8

2 Answers2

4

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
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
2

As Michael said and also I often use in error checking for bash scripts $LINENO - each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script.

So after certain command i would do:

 if [ $? = 0 ]; then
    echo "Command "Foo" finished successfully."
 else 
    echo "Error occurred on line $LINENO in command "Foo" with exit status  $?"
 fi

Something like this. Hope this helps.

Danila Ladner
  • 5,331
  • 22
  • 31
  • Thanks for the answer. I do not have problem with any new script code. But to existing script code, it is not realistic to change. I am looking for a way to see what goes wrong with existing scripts without touching them. – stanleyxu2005 Aug 04 '13 at 14:47