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?

2 Answers 2

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
1
  • Thanks. Call bash -x some_buggy_script is an option for me. Aug 4, 2013 at 14:48
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.

1
  • 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. Aug 4, 2013 at 14:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .