Bash - 获取命令(字符串)的值并查看它是否与另一个字符串匹配

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

正在尝试获取终端中 cyberghostvpn --status 显示的输出,即 No VPN connections found.VPN connection found.

我已经在 $VPN_status 上尝试 | grep -x "No VPN connections found." 并收到错误。甚至不记得过去几个小时我尝试过的一切。感觉这是一个简单的解决方案,但我只是想念它。这是代码($index 是从未在此摘录中列出的数组中随机选择的):

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

这个returns:

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

编辑 - 现在工作完美。这是更新后的代码 -

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

全部

您正在检查 return 代码(数字)而不是文本。

这可能会起作用:

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

在并非不合理的假设下,如果连接已启动,cyberghostvpn --status 会将退出代码设置为零,您可以简单地编写

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