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?

1

1 Answer 1

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/

2
  • 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? Commented Apr 5, 2013 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/… Commented Apr 6, 2013 at 4:04

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.