Shell script detecting errors from command called by script

1

I am calling applications from my shell script, which performs a number of important steps in sequence, one step being below:

for database in $( 
        echo 'show databases;' | 
        mysql --defaults-extra-file=/etc/sqlbackup/my.cnf \
              -e 'show databases' -s --skip-column-names|
        grep -vi information_schema )
do
  echo $database
done
exit 0

I am able to be able to log the output to the screen, that I am doing via the echo function.

My question is what would happen if an application (any command line called from the script), cannot connect and chucked an error such as:

`ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)`?

Are errors reported in a separate environment variable outside the string output, if so how can I detect this? How would one change the path the script takes depending on success or failure?

I am a .Net programmer and the best analogy i can make is where an exception is thrown and handeled:

catch (Exception e)
{
  // log the reason here: echo "error running database command: " + e.Description
}

Is there something similar to the above but for borne/bash shell?

g18c

Posted 2013-04-05T11:45:59.150

Reputation: 212

Read whole thing or only about redirection here and here. If none of that makes sense, you should probably check out bash for beginners and ABS. Happy learning!

– Ярослав Рахматуллин – 2013-04-05T13:40:44.697

Answers

3

There are three main streams of data: input, output and error.

  • Stdin is input

  • Stdout is output

  • Stderr is error

You can redirect the error messages by adding this 2>file.log at the end of your command.

This will write errors to log file which in turn you could read with tailf file.log - in a separate screen if you will.

$( echo 'show databases;' | /usr/bin/mysql --defaults-extra-file=/etc/sqlbackup/my.cnf -e 'show databases' -s --skip-column-names 2>>file.log |grep -vi information_schema )

If you need more details take a look in here: http://www.cyberciti.biz/faq/redirecting-stderr-to-stdout/

mnmnc

Posted 2013-04-05T11:45:59.150

Reputation: 3 637

Thanks for the answer. How about checking for error codes rather than just text to confirm an error has occured and take a different route in the script? – g18c – 2013-04-05T19:44:24.983

@g18c You could use the $? to check for exit code of last command. See the example here: http://blog.yimingliu.com/2009/01/01/check-last-exit-status-code-in-bash-shell/

– mnmnc – 2013-04-06T04:04:10.333