armor.navier
armor.navier

Reputation: 1

Bash script works in while but not in until?

This is very simple. I run this as a systemctl.

#!/bin/bash


until ping -c1 $1 www.google.com &>/dev/null
        do protonvpn c -f
done

my systemctl is:

### BEGIN INIT INFO
# Provides:          protonvpn
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: autostartvpn
### END INIT INFO

[Unit]
After=remote-fs.target

[Service]
ExecStart=/dir/startupscript

[Install]
WantedBy=default.target

It does not work (the upper script) when i execute it as systemctl, and it stops working generally after reboot for unknown reason.

I want to run this command protonvpn c -f on boot as soon as i get internet connection and i want it to loop until a connection is found (then kill-switch controls the app, and all works indefinitely).

Can you help me make it work?

Upvotes: 0

Views: 117

Answers (2)

l0b0
l0b0

Reputation: 58868

@hads0m has the right idea, but the loop pattern is also wrong.

until command1
do
    command2
done

does not do what you think. If command1 succeeds the first time then it never runs command2. If command1 does not succeed it'll run command2, and if that command runs in the background or exits it'll run command1 again. What you want instead is

until command1
do
    sleep 1
done
command2

to not run a busy loop and to only run command2 when the prerequisite is met.

Upvotes: 0

mtnezm
mtnezm

Reputation: 1027

If you want to run a service after having an active network connection, you can use this on your Systemd service file:

After=network-online.target

I think that would kill two birds with one stone, because that behaviour implies that you no longer should need to add any kind of check in your script to make sure it runs after network connection is established.

Upvotes: 1

Related Questions