简体   繁体   中英

Ensure successful execution of script on remote server

I have a script on a local system which invokes a script on the remote server (server A) to execute. The command in script which triggers remote server script looks like

ssh <user>@<server ip> "bash -s < ./shell_backup_trx_db.sh"

Script shell_backup_trx_db.sh on remote server takes database backup and puts it on server A file system. How can I ensure inside the script on local which uses the above command that the ssh command executed successfully and continue script execution ahead or else abort it?

As long as the remote script returns an appropriate exit code, you shouldn't have a problem to do this.

Just use the conditional control operator && which continues with the next command only if the previous command exited without an error:

ssh <user>@<server ip> "/path/to/shell_backup_trx_db.sh" && echo "Done with backup"

Edit: If you want to execute multiple commands based on whether the ssh command passes or fails, you can use an if..else..fi statement.

Example:

if ssh <user>@<server ip> "/path/to/shell_backup_trx_db.sh";
then
  echo "Backup completed successfully";
  ./next_script.sh;
else
  echo "Backup failed";
  exit;
fi

To exit your script when ssh fails (for whatever reason) you can use something like this.

if ! ssh ...; then
    echo ssh failed
    exit
fi

thanks to @Chirag and @Etan for their valuable answers, with their help ended up with.

  if ssh <user>@<server-ip> stat shell_backup_trx_db.sh \> /dev/null 2\>\&1
  then
    # Trigger Production Database back for both mysql and mongo.
   ssh <user>@<server-ip> "bash -s < ./shell_backup_trx_db.sh"

   echo "Database backup successfully completed."

   # Prompt user to check manually that database backup is completed successfully.
   read -p "Ensure database backup process is successfully completed. Login to dev/stg server and run 'ls command'. Press [Enter] key to continue execution."
  else 
    # Backup script could not be accessed, abort script execution any further. 
    echo "Back up script not found, aborting script execution, Please take backup before." 1>&2
    exit 1
  fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM