Running ssh remote command and grep for a string

冷暖自知 提交于 2019-12-05 00:20:26


I want to write script that will remotely run some ssh remote commands. All I need is to grep output of executed command for some special string which will mean that command executed successfully. For example when I run this:

ssh user@host "sudo /etc/init.d/haproxy stop"

I get output:

Stopping haproxy: [  OK  ]

All I need is to find "OK" string to ensure that command executed successfully. How can I do this?


Add grep and check exit status:

ssh user@host "sudo /etc/init.d/haproxy stop | grep -Fq '[  OK  ]'"
if [ "$#" -eq 0 ]; then
    echo "Command ran successfully."
    echo "Command failed."

You may also place grep outside.

ssh user@host "sudo /etc/init.d/haproxy stop" | grep -Fq '[  OK  ]'

Other ways to check exit status:

command && { echo "Command ran successfully."; }
command || { echo "Command failed."; }
if command; then echo "Command ran successfully."; else echo "Command failed."; fi

You can also capture output and compare it with case or with [[ ]]:

OUTPUT=$(exec ssh user@host "sudo /etc/init.d/haproxy stop")
case "$OUTPUT" in
*'[  OK  ]'*)
    echo "Command ran successfully."
    echo "Command failed."

if [[ $OUTPUT == *'[  OK  ]'* ]]; then
    echo "Command ran successfully."
    echo "Command failed."

And you can embed $(exec ssh user@host "sudo /etc/init.d/haproxy stop") directly as an expression instead of passing output to a variable if wanted.

If /etc/init.d/haproxy stop sends messages to stderr instead, just redirect it to stdout so you can capture it:

sudo /etc/init.d/haproxy stop 2>&1