Im running Lubuntu in a VM and trying to setup a script that runs every minute to check if the VPN is active, if not it turns everything off and on again. When i run the script manually everything works as intended, but when setup as a cronjob it fails at almost every turn.
First is that it cannot detect the routing table. When run manually it can see the tunnel but when run as a cron it fails and trys to quit everything.
The second is that it cannot execute the additional scripts/programs setup. It gets to the point of 'starting vpn' and then just quits, any output always stops here, but only as a cron, run manually it starts the vpn program.
I also cant seem to get the output to redirect to a file unless i append each echo statement with >>/home/localuser1/aqlog.txt. Adding that to the cron command does nothing.
#!/bin/bash
PATH=/home/localuser1/bin:/home/localuser1/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
echo "-----------------------------------Script started $(date)"
echo "Check VPN"
if [route | grep tun0 -c ]; then
echo "VPN running, check qbit"
if [pgrep qbit ]; then
echo "All active, no action needed"
else
echo "Not active, starting qbit"
nohup /usr/bin/qbittorrent >/dev/null &
fi
else
echo "no VPN, killing all"
pkill qbit
pkill pia
sleep 2
echo "Starting VPN"
nohup /home/localuser1/.pia_manager/pia_manager/run.sh >/dev/null &
echo "Waiting for VPN to start"
sleep 15
echo "Check VPN active"
if [route | grep tun0 -c]; then
echo "VPN active, starting qbit"
nohup /usr/bin/qbittorrent >/dev/null &
else
echo "No VPN, end of script"
fi
fi
echo "Exiting script"
I also have the following setup in crontab, where autoquit.sh is the arbitrary name of the script above:
# m h dom mon dow command
* * * * * /home/localuser1/autoquit.sh
[...]around commands if you don't understand what they're supposed to do. In particular, I doubt "everything works" when you're running this manually.[is an alias fortest. Consequently, (1)[should always be followed by a space (you don't happen to have a command named[route, do you), and (2)ifworks by checking the exit code of thetestcommand. Try this:if echo foo | grep -q foo; then echo found foo; fi. Which in turn works because the exit code ofecho foo | grep -q foois the exit code ofgrep.