Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporary operation in a temporary directory in shell script

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:

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"

What would be the best bang for the buck to do that in a Bash script?

Here is my current implementation. Any thoughts or suggestions?

here=$( pwd )
tdir=$( mktemp -d )
trap 'return_here' INT TERM EXIT
return_here () {
    cd "$here"
    [ -d "$tdir" ] && rm -rf "$tdir"
}

do_stuff # This may succeed, fail, change dir, or I may ^C it.
return_here
like image 948
JasonSmith Avatar asked Mar 18 '10 19:03

JasonSmith


2 Answers

Here you go:

#!/bin/bash
TDIR=`mktemp -d`

trap "{ cd - ; rm -rf $TDIR; exit 255; }" SIGINT

cd $TDIR
# do important stuff here
cd -

rm -rf $TDIR

exit 0
like image 200
JayM Avatar answered Oct 13 '22 08:10

JayM


The usual utility to get yourself a temporary directory is mktemp -d (and the -p option lets you specify a prefix directory).

I'm not sure if "I want to trap" was a question too, but bash does let you trap signals with (surprise!) trap - see the documentation.

like image 43
Cascabel Avatar answered Oct 13 '22 10:10

Cascabel