Bash conditional statement wrt time

Hi,

I'd like to start openvpn at boot only if time is not between 12am to 6am.

I've set system time correctly as per timezone

Thanks

#!/bin/sh

inst=$(grep -m1 -ao '[0-2][0-9]' /dev/urandom | head -n1 | sed 's/^0//;s/00/30/')

/etc/init.d/openvpn start $inst

Code above from here https://forum.openwrt.org/t/crontab-start-random-openvpn-instances/124829

that thread looks pretty complete, what's the actual question ?

id like to start

/etc/init.d/openvpn start $inst

at boot only if the time is not between 12am to 6am

you only need date +"%H"

this is obviously only needed if a reboot happens during the on time slot, everything else could be triggered from cron.

@pavelgl is a script guru, and might provide a turn-key ready solution :wink:

1 Like

Thank you, I think that should do it

#!/bin/sh
currenttime=$(date +%H:%M)
if [[ "$currenttime" > "23:59" ]] || [[ "$currenttime" < "05:59" ]]; then
   echo "rebooted without openvpn" > /dev/kmsg
else
   inst=$(grep -m1 -ao '[0-2][0-9]' /dev/urandom | head -n1 | sed 's/^0//;s/00/30/')
   /etc/init.d/openvpn start $inst
fi

time will never be > 23:59, the second check is probably enough.

could skip the %M, and use date +%H, then only check < "06",
if true start VPN, if not .... do noting.

2 Likes

Thanks, didn't work tho, dunno why

#!/bin/sh
currenttime=$(date +%H)
if [[ "$currenttime" > "24" ]] || [[ "$currenttime" < "06" ]]; then
   echo ">>>>>>>>>>>>>>>>>rebooted without openvpn" > /dev/kmsg
   echo $currenttime > /dev/kmsg
else
   inst=$(grep -m1 -ao '[0-2][0-9]' /dev/urandom | head -n1 | sed 's/^0//;s/00/30/')
   /etc/init.d/openvpn start $inst
   echo ">>>>>>>>>>>>>>>>>rebooted with openvpn" > /dev/kmsg
fi
[  133.431920] >>>>>>>>>>>>>>>>>rebooted without openvpn
[  133.437501] 15

Edit:
I guess I could make it between 1am to 6am to make things easier, thank you though :stuck_out_tongue:

if [ $currenttime -lt 06 ] should be all you need, since there no hour < 0 (, and > 24).

2 Likes

That worked, thank you.

Appreciate your help and support.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.