Tarley
Tarley

Reputation: 1

BASH Script to run command based in variable

Basically i have a script which i'm planning on running which will view the current status of an OpenVPN connection and re-connect if the status is not "VPN 'ibVPN is running" however it seems regardless of if the connection is running or not, it still tries to re-connect as part of this script.

I have manually run the command vpncon=("/etc/init.d/openvpn status") and then checked the results of this in terminal, which after running come out as " * VPN 'ibVPN' is running" so it looks to be passing the information over. I fear i'm not quite grasping how i then need to enter my if state text to match this.

Basically i want if $vpncon = * VPN 'ibVPN' is running then don't run the script/ If $vpncon is not * VPN 'ibVPN' is running, run the script.

Any help would be appreciated.

#!/bin/bash +x
while [ "true" ]
do
        vpncon=("/etc/init.d/openvpn status")
        if [[ $vpncon != *"VPN 'ibVPN' is running"* ]]; then
                echo "Disconnected, trying to reconnect..."
                (sleep 1s && sudo /etc/init.d/openvpn start ibVPN)
        else
                echo "Already connected !"
        fi
        sleep 30
done

Upvotes: 0

Views: 76

Answers (1)

edi9999
edi9999

Reputation: 20544

In your case vnpncon is the value "/etc/init.d/openvpn status" and not the result of that command. You should use $("command") instead. Also in your condition [[ $vpncon != *"VPN 'ibVPN' is running"* ]]; you should use double quotes for $vpncon.

This should work

#!/bin/bash +x
while true
do
        vpncon="$(/etc/init.d/openvpn status)"
        if [[ "$vpncon" != *"VPN 'ibVPN' is running"* ]]; then
                echo "Disconnected, trying to reconnect..."
                (sleep 1s && sudo /etc/init.d/openvpn start ibVPN)
        else
                echo "Already connected !"
        fi
        sleep 30
done

Upvotes: 1

Related Questions