.local-bin/scripts/setup_crontab.sh
2026-02-09 13:52:33 -05:00

94 lines
2.3 KiB
Bash
Executable file
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env bash
set -euo pipefail
CRONFILE="$HOME/.local/bin/mycronjobs.txt"
# -------- sanity check --------------------------------------------------------
if [[ ! -f "$CRONFILE" ]]; then
echo "$CRONFILE not found" >&2
exit 1
fi
# -------- load current crontab (may be empty) -------------------------------
TMP_OLD=$(mktemp)
crontab -l 2>/dev/null >"$TMP_OLD" || true
# -------- read existing cron jobs into array ---------------------------------
existing_jobs=()
while IFS= read -r line; do
# skip empty and comment lines
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
existing_jobs+=("$line")
done <"$TMP_OLD"
# -------- read new cron jobs into array --------------------------------------
new_jobs=()
while IFS= read -r line; do
# skip empty and comment lines
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
new_jobs+=("$line")
done <"$CRONFILE"
# -------- merge jobs ---------------------------------------------------------
added=()
skipped=()
TMP_NEW=$(mktemp)
cp "$TMP_OLD" "$TMP_NEW" # start with existing jobs
for job in "${new_jobs[@]}"; do
found=0
for existing in "${existing_jobs[@]}"; do
if [[ "$existing" == "$job" ]]; then
found=1
break
fi
done
if ((found)); then
skipped+=("$job")
else
echo "$job" >>"$TMP_NEW"
added+=("$job")
fi
done
# -------- install crontab if changed -----------------------------------------
if [ ${#added[@]} -eq 0 ]; then
echo " No new cron jobs to add; all jobs already present."
else
crontab "$TMP_NEW"
echo "✅ Added ${#added[@]} new cron job(s):"
for job in "${added[@]}"; do
echo " + $job"
done
fi
# Report skipped jobs
if [ ${#skipped[@]} -gt 0 ]; then
echo " Skipped ${#skipped[@]} existing job(s):"
for job in "${skipped[@]}"; do
echo " - $job"
done
fi
rm -f "$TMP_OLD" "$TMP_NEW"
# -------- ensure cron is running ---------------------------------------------
case "$(uname -s)" in
Linux)
if command -v systemctl >/dev/null &&
! systemctl --quiet is-active cron; then
echo " Starting cron via systemctl…"
sudo systemctl start cron
fi
;;
Darwin)
echo "✅ macOS: cron will run automatically via launchd."
;;
*)
echo "⚠️ Unknown OS; ensure cron or launchd is active."
;;
esac