解析 bash 输出

解析 bash 输出
#!/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

如果输入的话,前面的bash脚本会给出以下答案vpn stop

vpn stop如果有活动vpn连接,则运行:

[root@A ~]# vpn stop
Terminated

vpn stop如果没有活动vpn连接,则运行:

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

我想要实现的是:

vpn stop如果有活动vpn连接,则运行:

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

vpn stop如果没有活动vpn连接,则运行:

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

答案1

您必须检查停止命令的退出信号:

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 会将最后执行的命令的退出信号存储在$?变量上。按照标准,任何有价值的退出信号0都被认为是成功的,否则就是失败的。

编辑:我犯了一个小错字并改变了重定向器的顺序>&

相关内容