bash - shell脚本中临时目录下的临时操作

标签 bash shell temporary-files temporary-directory

我需要一个新的临时目录来在 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

最佳答案

给你:

#!/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

关于bash - shell脚本中临时目录下的临时操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2472629/

相关文章:

bash - 将 unix 输出发送到 csv 文件

linux - 根据条件查找最大的文件并将其复制到特定目录

ruby - 为什么这个简单的 Ruby 程序没有打印出我期望的结果?

python - matplotlib 的 savefig() 不能使用读写文件?

C++:获取临时文件,跨平台

python - paramiko ls 有几个文件输出被截断

Bash: `true` 的用法

unix - 在 shell 脚本中检查 unix 用户名和密码

linux - cgi-bin 中的 Perl 脚本不执行带参数的 shell 脚本

linux - 下面的脚本做了什么