Execute Script Based on Command Output – Bash Guide

bashcommand linescripts

I want to monitor the output of a command and whenever it contains a certain string I want to run another command.

Example: when command1 outputs 1234 I want to run command2

Best Answer

Typically this is accomplished with if statement and grep pipeline. Something like

$ if df | grep '/dev/sdb1' -q; then echo "Partition mounted"; fi
Partition mounted

Trick here, is that if statements operate on exit statuses of commands, and the exit status of the whole pipeline is the exit status of the last command. Of course grep -q will not print anything to the screen, but the zero exit status will tell you whether or not the command succeeded (i.e. grep found desired string in the output) or not if non-zero.

A different approach is via case statement, and command substitution, which I'd find perhaps more suitable where output is a single-line, and where you want to shoot for script portability between operating systems ( aka POSIX compliance ).

case "$(mountpoint /)" in 
    *"is a mountpoint"*) echo "Yup,it's a mount point alright"; 
                         stat /;; 

Third way, would be via again command-substitution and test command for exact match.

[ "$(command1 )" = "Some string"  ]

Or bash's extended test [[ for pattern matching:

# [[ $(command1) =~ ^pattern$ ]]
$ [[ "$( mountpoint /proc )" =~ .*is\ a\ mountpoint.*  ]] && echo "Yup"

Those can be used within if statement, or with conditional operators like &&, e.g. [ "$(echo test)" = "test" ] && df.

Best approach, I think would be to make it all a function so that you can pass your argument to the desired command, and perhaps reuse it later within if or case statement. So something like this:

        case "$(mountpoint "$1")" in 
        *"is a mountpoint"*) echo "Yup,"$1" is a mount point alright"; 
                             stat "$1";; 

Of course, keep in mind these are just slightly verbose, and perhaps unnecessary, but still examples of how it can be done. Adapt to your specific case as necessary. Keep in mind this is not exhaustive information,too.