Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running ssh remote command and grep for a string

Tags:

grep

bash

shell

ssh

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?

like image 247
Eazy Avatar asked Aug 18 '14 06:08

Eazy


1 Answers

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."
else
    echo "Command failed."
fi

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."
esac

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

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
like image 109
konsolebox Avatar answered Sep 28 '22 10:09

konsolebox