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
source share