Search code examples
bashsshcentos

IF when ssh conection down


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?


Solution

  • 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
    

    Just to to make it clear why help test is involve.

    help test | grep '^ *!'
    

    Output with a bang!

     ! EXPR         True if expr is false.