background-job 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #!/usr/bin/env bash
  2. NAME=""
  3. COMMAND_FILE=""
  4. ENV_FILE=""
  5. MAIL_NOTIFICATION=""
  6. PID=$$
  7. USAGE="Usage: `basename $0` [-h] [-n name] [-e env-file] [-m mail-address] COMMAND+"
  8. while getopts hn:e:m:N: OPT; do
  9. case "$OPT" in
  10. h)
  11. echo $USAGE
  12. exit 1
  13. ;;
  14. n)
  15. NAME=$OPTARG
  16. ;;
  17. e)
  18. ENV_FILE=$OPTARG
  19. ;;
  20. m)
  21. MAIL_NOTIFICATION=$OPTARG
  22. ;;
  23. \?)
  24. echo $USAGE >&2
  25. exit 1
  26. ;;
  27. esac
  28. done
  29. shift $((OPTIND - 1))
  30. if [ -z "${NAME}" ] ; then
  31. echo "A job name is required." >&2
  32. exit 1
  33. fi
  34. if [ $# -lt 1 ] ; then
  35. echo "A command is required." >&2
  36. exit 1
  37. fi
  38. RUN_SCRIPT=$(mktemp)
  39. cat <<EOF > "${RUN_SCRIPT}"
  40. #!/bin/sh
  41. FN="${RUN_SCRIPT}"
  42. JOB_NAME="${NAME}"
  43. MAIL_NOTIFICATION="${MAIL_NOTIFICATION}"
  44. OUTPUT_FILE=\$(mktemp)
  45. TIME_FILE=\$(mktemp)
  46. START_TIME=\$(date)
  47. EOF
  48. if [ -e "${ENV_FILE}" ] ; then
  49. cat "${ENV_FILE}" >> "${RUN_SCRIPT}"
  50. fi
  51. cat <<EOF >> "${RUN_SCRIPT}"
  52. env time -o \${TIME_FILE} $@ 2>&1 | tee \${OUTPUT_FILE}
  53. cat \${TIME_FILE}
  54. END_TIME=\$(date)
  55. EOF
  56. if [ ! -z "${MAIL_NOTIFICATION}" ] ; then
  57. cat <<EOF >> "${RUN_SCRIPT}"
  58. MESSAGE_FILE=\$(mktemp)
  59. cat <<EOM > "\${MESSAGE_FILE}"
  60. Job \${JOB_NAME} has completed. The output is attached.
  61. Start time: \${START_TIME}
  62. End time : \${END_TIME}
  63. Process Time/Usage Statistics:
  64. EOM
  65. cat "\${TIME_FILE}" >> "\${MESSAGE_FILE}"
  66. cat <<EOM >> "\${MESSAGE_FILE}"
  67. FN="${RUN_SCRIPT}"
  68. JOB_NAME="${NAME}"
  69. MAIL_NOTIFICATION="${MAIL_NOTIFICATION}"
  70. ENV_FILE="${ENV_FILE}"
  71. EOM
  72. mail -s "Job \${JOB_NAME} complete" -a "\${OUTPUT_FILE}" "\${MAIL_NOTIFICATION}" < "\${MESSAGE_FILE}"
  73. rm "\${MESSAGE_FILE}"
  74. EOF
  75. fi
  76. cat <<EOF >> "${RUN_SCRIPT}"
  77. rm "\${OUTPUT_FILE}"
  78. rm "\${TIME_FILE}"
  79. rm "\${FN}"
  80. EOF
  81. chmod +x ${RUN_SCRIPT}
  82. screen -d -S "job-${NAME}" -m ${RUN_SCRIPT}