bash shell脚本中临时目录的临时操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2472629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Temporary operation in a temporary directory in shell script
提问by JasonSmith
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:
我需要一个新的临时目录来在 shell 脚本中做一些工作。工作完成后(或者如果我中途终止工作),我希望脚本改回旧的工作目录并清除临时目录。在 Ruby 中,它可能如下所示:
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?
在 Bash 脚本中这样做最划算的是什么?
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
回答by JayM
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
回答by Cascabel
The usual utility to get yourself a temporary directory is mktemp -d(and the -poption lets you specify a prefix directory).
获得临时目录的常用实用程序是mktemp -d(并且该-p选项允许您指定前缀目录)。
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.
我不确定“我想捕获”是否也是一个问题,但是 bash 确实让您捕获信号(惊喜!)trap- 请参阅文档。
回答by Chris Johnsen
Assuming mktemp -dreturns a relative pathname, I would forget about $hereand do this instead:
假设mktemp -d返回一个相对路径名,我会忘记$here并改为这样做:
tdir=
cleanup() {
test -n "$tdir" && test -d "$tdir" && rm -rf "$tdir"
}
tdir="$(pwd)/$(mktemp -d)"
trap cleanup EXIT
trap 'cleanup; exit 127' INT TERM
# no need to call cleanup explicitly, unless the shell itself crashes, the EXIT trap will run it for you

