Advertisement
mogra

Try Blocks in Bash

Mar 25th, 2014
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.40 KB | None | 0 0
  1. #!/bin/bash
  2. . /etc/init.d/functions
  3.  
  4. # Use step(), try(), and next() to perform a series of commands and print
  5. # [  OK  ] or [FAILED] at the end. The step as a whole fails if any individual
  6. # command fails.
  7. #
  8. # Example:
  9. #     step "Remounting / and /boot as read-write:"
  10. #     try mount -o remount,rw /
  11. #     try mount -o remount,rw /boot
  12. #     next
  13. step() {
  14.     echo -n "$@"
  15.  
  16.     STEP_OK=0
  17.     [[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$
  18. }
  19.  
  20. try() {
  21.     # Check for `-b' argument to run command in the background.
  22.     local BG=
  23.  
  24.     [[ $1 == -b ]] && { BG=1; shift; }
  25.     [[ $1 == -- ]] && {       shift; }
  26.  
  27.     # Run the command.
  28.     if [[ -z $BG ]]; then
  29.         "$@"
  30.     else
  31.         "$@" &
  32.     fi
  33.  
  34.     # Check if command failed and update $STEP_OK if so.
  35.     local EXIT_CODE=$?
  36.  
  37.     if [[ $EXIT_CODE -ne 0 ]]; then
  38.         STEP_OK=$EXIT_CODE
  39.         [[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$
  40.  
  41.         if [[ -n $LOG_STEPS ]]; then
  42.             local FILE=$(readlink -m "${BASH_SOURCE[1]}")
  43.             local LINE=${BASH_LINENO[0]}
  44.  
  45.             echo "$FILE: line $LINE: Command \`$*' failed with exit code $EXIT_CODE." >> "$LOG_STEPS"
  46.         fi
  47.     fi
  48.  
  49.     return $EXIT_CODE
  50. }
  51.  
  52. next() {
  53.     [[ -f /tmp/step.$$ ]] && { STEP_OK=$(< /tmp/step.$$); rm -f /tmp/step.$$; }
  54.     [[ $STEP_OK -eq 0 ]]  && echo_success || echo_failure
  55.     echo
  56.  
  57.     return $STEP_OK
  58. }
  59.  
  60. prompt() {
  61.     echo -n $@
  62.     read -n1 val
  63.     echo
  64.     return $val
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement