Search code examples
bashbooleanstdoutrhelstderr

grep stderr and stdout of previous command


In bash script I need to check the stderr and stdout message of the command 1 and run command 2 if a string is found in message

Something like:

command 1

if [ $? != 0 ] and grep stderr and stdout of command 1 and if it contains hello world; then run

command 2

fi

Solution

  • Redirect the output of command1 to a file and then use grep to check if the files contains the string 'hello world'

    command1 > /tmp/stdout.$$ 2>/tmp/stderr.$$
    if [ $? -ne 0 ] && grep 'hello world' /tmp/stdout.$$ /tmp/stderr; then
        command2;
    fi
    

    You could also combine into a single file using the "2>&1" syntax (redirect file descriptor 2 (stderr) to file descriptor 1 (stdout).

    command1 > /tmp/stdout-stderr.$$ 2>&1
    if [ $? -ne 0 ] && grep 'hello world' /tmp/stdout-stderr.$$; then
        command2;
    fi