skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. You probably want to implement this in your cron tab (run crontab -e):

    */5   *   *   *   *   systemctl -q is-active sshd || rm -f jamaica.sh
    

    This runs every five minutes. Using short-circuiting logic, rm is only run when the systemd system controller reports SSH is not active. (I removed -r since it is only needed to remove a directory.)

    If you’re not running systemd, change the first command (before the ||) to be service sshd status >/dev/null.

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

    */5  *  *  *  *  root  systemctl -q is-active sshd || service sshd restart >/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.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search