bash - Running ssh remote command and grep for a string -
i want write script remotely run ssh remote commands. need grep output of executed command special string mean command executed successfully. example when run this:
ssh user@host "sudo /etc/init.d/haproxy stop" i output:
stopping haproxy: [ ok ] all need find "ok" string ensure command executed successfully. how can this?
add grep , check exit status:
ssh user@host "sudo /etc/init.d/haproxy stop | grep -fq '[ ok ]'" if [ "$#" -eq 0 ]; echo "command ran successfully." else echo "command failed." fi you may place grep outside.
ssh user@host "sudo /etc/init.d/haproxy stop" | grep -fq '[ ok ]' other ways check exit status:
command && { echo "command ran successfully."; } command || { echo "command failed."; } if command; echo "command ran successfully."; else echo "command failed."; fi you can capture output , compare case or [[ ]]:
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 ]'* ]]; echo "command ran successfully." else echo "command failed." fi and can embed $(exec ssh user@host "sudo /etc/init.d/haproxy stop") directly expression instead of passing output variable if wanted.
if /etc/init.d/haproxy stop sends messages stderr instead, redirect stdout can capture it:
sudo /etc/init.d/haproxy stop 2>&1
Comments
Post a Comment