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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -