0
#!/bin/bash

start(){
  printf 'Real IP: %s\n' "$(curl -s ifconfig.co)"
  set -- /etc/openvpn/ovpn_tcp/*.nordvpn.com.tcp.ovpn
  shift $(( RANDOM % $# ))
  screen -S vpn -dm openvpn "$1" # connect
  sleep 5 # wait for connection
  printf 'VPN IP: %s\n' "$(curl -s ifconfig.co)"
}
stop(){
  screen -S vpn -X quit
  pkill -f ovpn
}
status(){
  printf 'Current IP: %s\n' "$(curl -s ifconfig.co)"
}

case "$1" in
start)
    if screen -ls | grep -w vpn &> /dev/null; then
      echo "VPN Already Connected";
      status
    else
      start
    fi
    ;;
stop)
    stop
    ;;
*)
    status
    ;;
esac

The previous bashscript give the following answer in case if vpn stop typed.

run of vpn stop if there's active vpn connection:

[root@A ~]# vpn stop
Terminated

run of vpn stop if there's not active vpn connection:

[root@A ~]# vpn stop
No screen session found.
Terminated

What I'm looking to achieve is:

run of vpn stopif there's active vpn connection:

[root@A ~]# vpn stop
VPN Connection Closed Successfully 

run of vpn stop if there's not active vpn connection:

[root@A ~]# vpn stop
There's No Active VPN Connection to stop it.
0

You have to check for the exit signal of the stop command:

stop(){
  screen -S vpn -X quit >/dev/null 2>&1
  if [ "$?" == 0 ]; then
    echo "VPN Connection Closed Successfully"
  else
    echo "There's No Active VPN Connection to stop it."
  fi

   pids=( $(pgrep -f ovpn) )
   for pid in "${pids[@]}"; do
    if [[ $pid != $$ ]]; then
     kill "$pid"
  fi
done
}

Bash will store the exit signal of the last executed command on the $? variable. By standard, any exit signal with value 0 is to be considered as being successful and anything otherwise is a failure.

EDIT: I made a small typo and switched the order of the >& redirector.

  • the command will check the exit signal of the screen quit command. Can you run the command manually using screen -S vpn -X quit && echo $? and say what the output is, please? – fboaventura May 22 at 7:26
  • @αԋɱҽԃαмєяιcαη sorry, I made a small typo and switched the order of the redirector. You need >& instead of &> – fboaventura May 22 at 15:17
  • Can you run the script with bash -x vpn stop and share the output, please? – fboaventura May 22 at 17:08
  • Can you run it with a live vpn connection? – fboaventura May 22 at 18:19
  • Let us continue this discussion in chat. – fboaventura May 22 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.