Last active
April 28, 2024 22:27
-
-
Save themactep/06f951da3fc05693871cc15aa243dff5 to your computer and use it in GitHub Desktop.
Generate cron job lines from sunrise and sunset time provided by api.sunrise-sunset.org
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# | |
# Set cron jobs by sunset and sunrise | |
# 2023, Paul Philippov <paul@themactep.com> | |
# | |
# Do not forget to tip the API provider! | |
# https://www.buymeacoffee.com/sunrisesunsetapi | |
# | |
# Geographic coordinates of your place | |
lat="42.511398" | |
lng="14.145070" | |
crontab_file="/etc/crontabs/root" | |
at_sunrise_marker="# at sunrise (autogenerated)" | |
at_sunset_marker="# at sunset (autogenerated)" | |
# retrieve and parse sunset and sunrise time | |
json=$(curl --silent --url "https://api.sunrise-sunset.org/json?lat=${lat}&lng=${lng}&formatted=0") | |
sunrise_hour=$(jsonfilter -s "$json" -e @.results.sunrise | awk -F[T:] '{print $2}') | |
sunrise_minute=$(jsonfilter -s "$json" -e @.results.sunrise | awk -F[T:] '{print $3}') | |
sunset_hour=$(jsonfilter -s "$json" -e @.results.sunset | awk -F[T:] '{print $2}') | |
sunset_minute=$(jsonfilter -s "$json" -e @.results.sunset | awk -F[T:] '{print $3}') | |
# create a working copy of crontab in ram | |
tmp_crontab_file=$(mktemp) | |
cp "$crontab_file" "$tmp_crontab_file" | |
# delete old jobs | |
sed -i "/$at_sunrise_marker/,+1d" "$tmp_crontab_file" | |
sed -i "/$at_sunset_marker/,+1d" "$tmp_crontab_file" | |
# create new marked jobs | |
{ | |
echo "$at_sunset_marker" | |
printf "%02d %02d * * * daynight night\n" "$sunset_minute" "$sunset_hour" | |
echo "$at_sunrise_marker" | |
printf "%02d %02d * * * daynight day\n" "$sunrise_minute" "$sunrise_hour" | |
} >>"$tmp_crontab_file" | |
# replace actual crontab file with the updated one | |
cp "$tmp_crontab_file" "$crontab_file" | |
echo "Done" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment