shell脚本中临时目录下的临时操作
我需要一个新的临时目录来在 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"
在 Bash 脚本中这样做最划算的是什么?
这是我当前的实现。有什么想法或建议吗?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
干得好:
Here you go:
为自己获取临时目录的常用实用程序是
mktemp -d
(并且-p
选项允许您指定前缀目录)。我不确定“我想捕获”是否也是一个问题,但 bash 确实允许您使用(惊讶!)
trap
捕获信号 - 请参阅文档。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.假设 mktemp -d 返回相对路径名,我会忘记 $here 并执行以下操作:
Assuming
mktemp -d
returns a relative pathname, I would forget about$here
and do this instead: