Home > Back-end >  Bash - Grabbing value of a command (string) and seeing if it matches another string
Bash - Grabbing value of a command (string) and seeing if it matches another string

Time:12-02

Attempting to grab the output displayed by cyberghostvpn --status in the terminal, which is either No VPN connections found. or VPN connection found.

I've tried | grep -x "No VPN connections found." on $VPN_status and received errors. Can't even remember everything I've tried for the past couple hours. Feel like this is a simple solution but I'm just missing it. Here is the code ($index is a random selection from an array not listed in this excerpt):

VPN_status="$(cyberghostvpn --status)"
echo $VPN_status
if [[ $? == "No VPN connetions found." ]]; then
    echo "Connecting to VPN."
    cyberghostvpn --country-code $index --server-type traffic --openvpn --connect
else
    echo "You are connected to the VPN already."
fi

This returns:

No VPN connections found.
You are connected to the VPN already.

CodePudding user response:

You are checking against the return code (a number) not the text.

This will probably work:

VPN_status="$(cyberghostvpn --status)"
echo $VPN_status
if [[ $VPN_status == "No VPN connetions found." ]]; then
    echo "Connecting to VPN."
    cyberghostvpn --country-code $index --server-type traffic --openvpn --connect
else
    echo "You are connected to the VPN already."
fi

CodePudding user response:

Under the not unreasonable assumption, that cyberghostvpn --status sets exit code zero if the connection is up, you could simply write

if cyberghostvpn --status
then
  echo You are connected
else
  echo Trying to connect 
  ....
fi
  • Related