Bash: How to check if a number of operations finished successfully? Bash: How to check if a number of operations finished successfully? shell shell

Bash: How to check if a number of operations finished successfully?


If you need to fail if any of the operations fails, then simply do set -e at the top of the scripts. Then it will fail as soon as any step fails.

If you are ok with any individual step failures, but only want to keep track of the number of failures then you can try this:

success_count=0scp $workdir/$site$dom.conf root@$srv13:$workdir && success_count=$((success_count+1))scp $workdir/$site$dom.conf root@$srv179:$workdir && success_count=$((success_count+1))ssh root@$srv13 "hostname ; service httpd restart" && success_count=$((success_count+1))ssh root@localhost "hostname ; service httpd restart" && success_count=$((success_count+1))ssh root@$srv179 "hostname ; service httpd restart" && success_count=$((success_count+1))ssh root@$srv201 "hostname ; service named restart" && success_count=$((success_count+1))echo "Num ops succeeded = $success_count"

You can even pull it into a function, like:

exec_with_count() {    "$@" && success_count=$((success_count+1))}exec_with_count scp $workdir/$site$dom.conf root@$srv13:$workdirexec_with_count scp $workdir/$site$dom.conf root@$srv179:$workdir...echo "Num ops succeeded = $success_count"


You can chain the operations with && but maybe you ruled that out already too?

scp $workdir/$site$dom.conf root@$srv13:$workdir &&  scp $workdir/$site$dom.conf root@$srv179:$workdir &&  ssh root@$srv13 "hostname service httpd restart" &&  ssh root@localhost "hostname  service httpd restart" &&  ssh root@$srv179 "hostname service httpd restart" &&  ssh root@$srv201 "hostname service named restart" &&  echo "All ok"