123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- #!/usr/bin/env bash
- NAME=""
- COMMAND_FILE=""
- ENV_FILE=""
- MAIL_NOTIFICATION=""
- PID=$$
- USAGE="Usage: `basename $0` [-h] [-n name] [-e env-file] [-m mail-address] COMMAND+"
- while getopts hn:e:m:N: OPT; do
- case "$OPT" in
- h)
- echo $USAGE
- exit 1
- ;;
- n)
- NAME=$OPTARG
- ;;
- e)
- ENV_FILE=$OPTARG
- ;;
- m)
- MAIL_NOTIFICATION=$OPTARG
- ;;
- \?)
- echo $USAGE >&2
- exit 1
- ;;
- esac
- done
- shift $((OPTIND - 1))
- if [ -z "${NAME}" ] ; then
- echo "A job name is required." >&2
- exit 1
- fi
- if [ $# -lt 1 ] ; then
- echo "A command is required." >&2
- exit 1
- fi
- RUN_SCRIPT=$(mktemp)
- cat <<EOF > "${RUN_SCRIPT}"
- #!/bin/sh
- FN="${RUN_SCRIPT}"
- JOB_NAME="${NAME}"
- MAIL_NOTIFICATION="${MAIL_NOTIFICATION}"
- OUTPUT_FILE=\$(mktemp)
- TIME_FILE=\$(mktemp)
- START_TIME=\$(date)
- EOF
- if [ -e "${ENV_FILE}" ] ; then
- cat "${ENV_FILE}" >> "${RUN_SCRIPT}"
- fi
- cat <<EOF >> "${RUN_SCRIPT}"
- env time -o \${TIME_FILE} $@ 2>&1 | tee \${OUTPUT_FILE}
- cat \${TIME_FILE}
- END_TIME=\$(date)
- EOF
- if [ ! -z "${MAIL_NOTIFICATION}" ] ; then
- cat <<EOF >> "${RUN_SCRIPT}"
- MESSAGE_FILE=\$(mktemp)
- cat <<EOM > "\${MESSAGE_FILE}"
- Job \${JOB_NAME} has completed. The output is attached.
- Start time: \${START_TIME}
- End time : \${END_TIME}
- Process Time/Usage Statistics:
- EOM
- cat "\${TIME_FILE}" >> "\${MESSAGE_FILE}"
- cat <<EOM >> "\${MESSAGE_FILE}"
- FN="${RUN_SCRIPT}"
- JOB_NAME="${NAME}"
- MAIL_NOTIFICATION="${MAIL_NOTIFICATION}"
- ENV_FILE="${ENV_FILE}"
- EOM
- mail -s "Job \${JOB_NAME} complete" -a "\${OUTPUT_FILE}" "\${MAIL_NOTIFICATION}" < "\${MESSAGE_FILE}"
- rm "\${MESSAGE_FILE}"
- EOF
- fi
- cat <<EOF >> "${RUN_SCRIPT}"
- rm "\${OUTPUT_FILE}"
- rm "\${TIME_FILE}"
- rm "\${FN}"
- EOF
- chmod +x ${RUN_SCRIPT}
- screen -d -S "job-${NAME}" -m ${RUN_SCRIPT}
|