Home > Software engineering >  IF when ssh conection down
IF when ssh conection down

Time:09-07

I'm connected to a server with CentOS 6.10 from ssh user@server......

And, i have a bash script on this server, named by "jamaica.sh", the code is....

#!/bin/bash
rm -rf jamaica.sh

Simple, but que question is. I need to found a command to delete jamaica.sh if ssh conection down, when i run "exit" or when i close the window.

Something like that...

if $(service sshd status | grep "running") == false
then
rm -rf jamaica.sh
fi

Can i found a way to do this?

CodePudding user response:

You probably want to implement this in your cron tab (run crontab -e):

*/5   *   *   *   *   service sshd status >/dev/null || rm -f jamaica.sh

This runs every five minutes. Using short-circuiting logic, rm is only run if grep fails to find a match. (-r is only needed if the target is a directory.)

If you are root, you could try restarting sshd first (in /etc/crontab):

*/5  *  *  *  *  root  service sshd status >/dev/null || service sshd start >/dev/null 2>&1 || rm -f jamaica.sh

(It's also best to put longer commands into scripts that you call from cron rather than putting the logic in there directly. This second example pushes it, at least for folks like me who insist upon 80-column widths.)

CodePudding user response:

You could try to negate the exit status with a bang !, something like.

if ! service sshd status 2>&1 | grep -Fq 'running'; then
  rm -rf jamaica.sh
fi

As per Charles Duffy's comment the grep is not needed.

if ! service sshd status >/dev/null; then
   rm -rf jamaica.sh
fi

See

help test | grep '^ *!'

grep --help

  • Related