Grim
Grim

Reputation: 33

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

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.

EDIT - Working perfectly now. Here is the updated code -

array=("AD" "AE" "AL" "AM" "AR" "AT" "BA" "BD" "BE" "BG" "BR" "BS" "BY" "CH" "CL" "CN" "CO" "CR" "CY" "CZ" "DE" "DK" "DZ" "EE" "EG" "ES" "FI" "FR" "GB" "GE" "GL" "GR" "HK" "HR" "HU" "ID" "IE" "IL" "IM" "IN" "IR" "IS" "IT" "JP" "KE" "KH" "KR" "KZ" "LI" "LK" "LT" "LU" "LV" "MA" "MC" "MD" "ME" "MK" "MN" "MO" "MT" "MX" "MY" "NG" "NL" "NO" "NZ" "PA" "PH" "PK" "PL" "PT" "QA" "RO" "RS" "RU" "SA" "SE" "SG" "SI" "SK" "TH" "TR" "TW" "UA" "US" "VE" "VN" "ZA")
size="${#array[@]}"
index=$[ $RANDOM % $size ]
Country=${array[$index]}
VPN_status="$(cyberghostvpn --status)"
VPN_connect="$(cyberghostvpn --openvpn --traffic --country-code $Country --connect)"
echo $VPN_status
if [[ $VPN_status == "No VPN connections found." ]]; then
    echo "Connecting to VPN."
    $VPN_connect
    echo "New country is $Country"
elif [[ $VPN_status == "VPN connection found." ]]; then
    echo "Changing country..."
    echo "New country is $Country"
else
    echo "This shouldn't have happened..."
fi

ty all

Upvotes: 0

Views: 102

Answers (2)

user1934428
user1934428

Reputation: 22291

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

Upvotes: 1

Mikael Kjær
Mikael Kjær

Reputation: 700

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

Upvotes: 2

Related Questions