Skip to content

Instantly share code, notes, and snippets.

@qxj
Created May 16, 2015 02:04
Show Gist options
  • Save qxj/4550dbf5d6cfc59ed13f to your computer and use it in GitHub Desktop.
Save qxj/4550dbf5d6cfc59ed13f to your computer and use it in GitHub Desktop.
Collect *.cron in the directory, and then APPEND to the original crontab
#!/usr/bin/env bash
# @(#) crontab.sh Time-stamp: <Julian Qian 2015-05-15 18:14:28>
# Copyright 2015 Julian Qian
# Author: Julian Qian <junist@gmail.com>
# Version: $Id: crontab.sh,v 0.1 2015-05-14 10:53:03 jqian Exp $
#
# Collect *.cron in the directory, and then APPEND to the original crontab
# TODO fix potential confliction when more than one crontab.sh instances are running concurrently.
THIS_PATH=$(readlink -f $0)
cd $(dirname $THIS_PATH)
start_flag="###{{{ AUTO GENERATED BY ${THIS_PATH}, DONOT DELETE THIS LINE!"
end_flag="###}}} AUTO GENERATED BY ${THIS_PATH}, DONOT DELETE THIS LINE!"
REPO_PATH=$(dirname $(dirname $THIS_PATH))
task_file=$(mktemp)
echo $start_flag > $task_file
datetime=$(date "+%Y-%m-%d %H:%m:%S")
echo "### Below tasks are generated at $datetime automatically." >> $task_file
echo "### If you want to maintain your own cron tasks, please add them" >> $task_file
echo "### ABOVE or AFTER this section." >> $task_file
echo "###" >> $task_file
for cron in $(find . -maxdepth 1 -name "*.cron" -type f | sort); do
echo "
################ $cron ################
" >> $task_file
sed "s!\$REPO_PATH!$REPO_PATH!g" $cron >> $task_file
done
echo "
" >> $task_file
echo $end_flag >> $task_file
# back original crontab
bak_file=$(mktemp)
is_interal=no
crontab -l | while read line;
do
if [[ $line == $start_flag ]];
then
is_interal=yes
fi
if [[ $is_interal == no ]];
then
echo "$line" >> $bak_file
fi
if [[ $line == $end_flag ]];
then
is_interal=no
fi
done
cron_file=$(mktemp)
cat $bak_file > $cron_file
cat $task_file >> $cron_file
cat $cron_file > crontab.txt
crontab $cron_file
rm $task_file $bak_file $cron_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment