Skip to content

Instantly share code, notes, and snippets.

@karfau
Last active February 20, 2018 19:28
Show Gist options
  • Save karfau/053acab10ecea3c4d0f9ec858a6b35b2 to your computer and use it in GitHub Desktop.
Save karfau/053acab10ecea3c4d0f9ec858a6b35b2 to your computer and use it in GitHub Desktop.
executes the parameters, checks the exit code, prints log file to stderr in case exit code is not 0, helpful for running crontab

CTR (crontab-runner)

Executes the parameters, checks the exit code, prints log file to stderr in case exit code is not 0.

Helpful for running cron jobs to only get mails on errors, but with full logs attached

Cloning the gist

git clone https://gist.github.com/053acab10ecea3c4d0f9ec858a6b35b2.git ctr

proving it works

with exit code != 0

./ctr/crrontab-runner.sh ./ctr/test-failing.sh

will print all possible information to stderr (and exit with the same error code as test-failing.sh)

with exit code == 0

./ctr/crrontab-runner.sh ./ctr/test-success.sh

will only print the executed command and the logfile it writes to to stdout

#!/usr/bin/env bash
cd "$(dirname "$0")" && mkdir -p logs
DATE=$(date "+%FT%H-%M-%S")
LOGFILE="$(pwd)/logs/$(basename "$1").${DATE}.log"
log_on_error () {
EC=$?
if [[ ${EC} -ne 0 ]] ; then
>&2 echo "log from 'bash \"${COMMANDS}\"' written to ${LOGFILE}"
>&2 cat "${LOGFILE}"
>&2 echo "exit code was ${EC}"
exit ${EC}
fi
}
trap log_on_error EXIT
COMMANDS=${*:1}
echo "running: 'bash \"${COMMANDS}\"' writing to ${LOGFILE}"
bash "${COMMANDS}" > "${LOGFILE}" 2>&1
#!/usr/bin/env bash
set -xe
pwd
exit 15
#!/usr/bin/env bash
set -xe
pwd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment