Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
    
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! –  Ярослав Рахматуллин Apr 5 '13 at 13:40

1 Answer 1

up vote 3 down vote accepted

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/

share|improve this answer
    
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 Apr 5 '13 at 19:44
    
@g18c You could use the $? to check for exit code of last command. See the example here: blog.yimingliu.com/2009/01/01/… –  mnmnc Apr 6 '13 at 4:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.