Running remote ssh and grep command for string

I want to write a script that will remotely run some remote ssh commands. All I need is grep the output of the executable command for some special line, which will mean that the command completed successfully. For example, when I run this:

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

I get the output:

 Stopping haproxy: [ OK ] 

All I need to do is find the “OK” line to make sure the command completed successfully. How can i do this?

+5
source share
1 answer

Add grep and check the 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 can 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 the 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 the output to a variable if you want.

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 
+5
source

Source: https://habr.com/ru/post/1200563/


All Articles