if the statement with variable comparison does not work in bash shell

advertisements

I'm trying to write a very simple script to check whether iptables are already updated for Synergy to work. The current script is:

if [[ $SYNERGY = "yes" ]]
then
    echo "Synergy is active"
else
    sudo iptables -I INPUT -p tcp --dport 24800 -j ACCEPT
    export SYNERGY=yes
fi

But it does not work (I'm always asked for the sudo password each time I open a new terminal)
I also tried with this modified version, but the result is the same

syn="yes"
if [ "$SYNERGY" = "$syn" ]
then
    echo "Synergy is active"
else
    sudo iptables -I INPUT -p tcp --dport 24800 -j ACCEPT
    export SYNERGY=yes
fi

Where is the issue?


If you are expecting this to be run from one terminal/shell session and to affect other unrelated terminals/shell sessions then the issue is that that isn't how export works.

export sets the variable in the environment of the current process so that any processes spawned from this process also have it in their environment. Notice how I said "spawned from"? It only applies to processes that process spawns. Unrelated processes aren't affected.

If you want something globally checkable then you either need a flag/lock/state file of some sort or an actual runtime check of the iptables configuration.