SHARE
TWEET

Untitled

a guest Jul 18th, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2.  
  3. #####################################################
  4. # An example of using a trap to cleanup a temporary #
  5. # even during errors or early script exit.          #
  6. #####################################################
  7.  
  8. # an easy way to observe the tempfile:
  9. #        watch "command ls -l -tc --reverse /tmp | tail"
  10.  
  11. declare sim_pipeerr=false
  12. declare sim_earlyexit=false
  13. declare -i do_something_delay=3
  14.  
  15. while true ; do
  16.     case "$1" in
  17.         -p)          sim_pipeerr=true           ; shift   ;;
  18.         -e)          sim_earlyexit=true         ; shift   ;;
  19.         -d)          do_something_delay=$2      ; shift 2 ;;
  20.         -h | --help) echo "Usage: $0 [-p] [-e]" ; exit 0  ;;
  21.         --) shift ; break ;;
  22.         -*) echo "bad opt: $1" ; exit 1 ;;
  23.         *) break ;;
  24.     esac
  25. done
  26.  
  27. create_tmpfile() {
  28.     mktemp --tmpdir="${TMPDIR:-/tmp}" --suffix=".tmp" "$(basename "$0")"-XXXXXX
  29. }
  30.  
  31. do_something() {
  32.     echo "Doing something with: '$1'"
  33.  
  34.     if [[ -n "$do_something_delay" ]] ; then
  35.         echo "Sleeping for $do_something_delay ..."
  36.         sleep $do_something_delay
  37.     fi
  38.  
  39.     if $sim_pipeerr ; then
  40.         echo "Ooops, pipeline error in do_something!"
  41.         : | false
  42.     fi
  43.  
  44.     if $sim_earlyexit ; then
  45.         echo "Oops, do_something called exit early!"
  46.         exit 1
  47.     fi
  48. }
  49.  
  50. work_with_temp_file() {
  51.     local tmpfile="$(create_tmpfile)"
  52.     trap "rm -f '${tmpfile}'" RETURN EXIT
  53.  
  54.     # use $tmpfile
  55.     do_something "${tmpfile}"
  56.  
  57.     # don't need to remember to rm $tmpfile at each repossible return point
  58.     # don't need to worry about do_something failing or exiting early
  59. }
  60.  
  61. work_with_temp_file
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top