Skip to content

Instantly share code, notes, and snippets.

@smoser
Last active May 29, 2019 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smoser/ee1687c231f5a125669374ac0a732a45 to your computer and use it in GitHub Desktop.
Save smoser/ee1687c231f5a125669374ac0a732a45 to your computer and use it in GitHub Desktop.
cronrun: run command with logging for crontab entries

cronrun : run command in cron

I often have errors where running a command from cron wasn't the same as running it from the command line. This is a small/silly attempt to remove those descrepencies and be able to just copy and paste what was in cron and expect that is the same.

I just put cronrun in /usr/local/bin and set it executable, and then set PATH in my crontab to include /usr/local/bin.

cronrun basically does:

  • set any environment i want (add ~/bin to path)

  • support '--logname=yourlog.log' and redirect output there so you don't have to read mail

  • support --logname=foo-YYYYMMDD.log replacing with current date.

  • execute the command provided.

     $ crontab -l
     PATH=/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
     03 0-23/2 * * * cronrun --quiet --logname=my-command.log my-command my-args
    
#!/bin/sh
# https://gist.github.com/smoser/ee1687c231f5a125669374ac0a732a45
export PATH=$HOME/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
[ "$1" = "--quiet" ] && shift && quiet=true || quiet=false
if [ "${1%=*}" = "--logname" ]; then
LOGDIR=${LOGDIR:-$HOME/cronlogs}
lname_in=${1#*=}
# replace YYYYMMDD with the date formated in that way.
yyyymmdd=$(date +%Y%m%d)
logname=$(echo "$lname_in" | sed "s/YYYYMMDD/${yyyymmdd}/")
shift
ldir=${LOGDIR}/
[ "${logname#/}" = "${logname}" ] || ldir=""
if [ "${lname_in}" = "${logname}" ]; then
lfile=${ldir}${logname}
$quiet || echo "# $@" >> "${lfile}"
else
[ -z "${ldir}" -o -d "${ldir}" ] || mkdir "${ldir}"
lfile="${ldir}${logname}"
i=0;
while lfile="${ldir}${logname}.${i}.log" && [ -e "${lfile}" ]; do
i=$((${i}+1))
done
fi
exec >>"$lfile" 2>&1
fi
exec "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment