title: Temporary operation in a temporary directory in shell script
body: <p>I need a fresh temporary directory to do some work in a shell script. When the work is done (or if I kill the job midway), I want the script to change back to the old working directory and wipe out the temporary one. In Ruby, it might look like this:</p>
  
  <pre><code>require 'tmpdir'
  
  Dir.mktmpdir 'my_build' do |temp_dir|
    puts "Temporary workspace is #{temp_dir}"
    do_some_stuff(temp_dir)
  end
  
  puts "Temporary directory already deleted"
  </code></pre>
  
  <p>What would be the best bang for the buck to do that in a Bash script?</p>
  
  <p>Here is my current implementation. Any thoughts or suggestions?</p>
  
  <pre><code>here=$( pwd )
  tdir=$( mktemp -d )
  trap 'return_here' INT TERM EXIT
  return_here () {
      cd "$here"
      [ -d "$tdir" ] &amp;&amp; rm -rf "$tdir"
  }
  
  do_stuff # This may succeed, fail, change dir, or I may ^C it.
  return_here
  </code></pre>