bash 如何创建临时目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4632028/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:03:01  来源:igfitidea点击:

How to create a temporary directory?

bashtemporary-directory

提问by Xiè Jìléi

I use to create a tempfile, delete it and recreate it as a directory:

我用来创建一个tempfile,删除它并将其重新创建为目录:

tmpnam=`tempfile`
rm -f $tmpnam
mkdir "$tmpnam"

The problem is, another process may get a same name X, if it accidently executes tempfile after one process rm -f Xand just before mkdir X.

问题是,如果另一个进程X在一个进程之后rm -f X和之前不小心执行了临时文件,它可能会获得相同的名称mkdir X

回答by moinudin

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

使用mktemp -d. 它使用随机名称创建一个临时目录,并确保该文件不存在。但是,您需要记住在使用后删除该目录。

回答by Ortwin Angermeier

For a more robust solution i use something like the following. That way the temp dir will always be deleted after the script exits.

对于更强大的解决方案,我使用如下内容。这样,脚本退出后,临时目录将始终被删除。

The cleanup function is executed on the EXITsignal. That guarantees that the cleanup function is always called, even if the script aborts somewhere.

清除函数在EXIT信号上执行。这保证了清除函数总是被调用,即使脚本在某处中止。

#!/bin/bash    

# the directory of the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# the temp directory used, within $DIR
# omit the -p parameter to create a temporal directory in the default location
WORK_DIR=`mktemp -d -p "$DIR"`

# check if tmp dir was created
if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
  echo "Could not create temp dir"
  exit 1
fi

# deletes the temp directory
function cleanup {      
  rm -rf "$WORK_DIR"
  echo "Deleted temp working directory $WORK_DIR"
}

# register the cleanup function to be called on the EXIT signal
trap cleanup EXIT

# implementation of script starts here
...

Directory of bash script from here.

bash 脚本的目录来自这里

Bash traps.

重击陷阱

回答by Emmett Butler

My favorite one-liner for this is

我最喜欢的单线是

cd $(mktemp -d)

回答by jreisinger

The following snippet will safely create a temporary directory (-d) and store its name into the TMPDIR. (An example use of TMPDIRvariable is shown later in the code where it's used for storing original files that will be possibly modified.)

以下代码段将安全地创建一个临时目录 ( -d) 并将其名称存储到TMPDIR. (TMPDIR稍后在代码中显示了变量的使用示例,它用于存储可能会被修改的原始文件。)

The first trapline executes exit 1command when any of the specified signalsis received. The second trapline removes (cleans up) the $TMPDIRon program's exit (both normal and abnormal). We initialize these traps after we check that mkdir -dsucceeded to avoid accidentally executing the exit trap with $TMPDIRin an unknown state.

当接收到任何指定的信号时,第一trap行执行exit 1命令。第二行删除(清理)程序的退出(正常和异常)。我们在检查成功后初始化这些陷阱,以避免意外执行处于未知状态的退出陷阱。trap$TMPDIRmkdir -d$TMPDIR

#!/bin/bash

# Create a temporary directory and store its name in a variable ...
TMPDIR=$(mktemp -d)

# Bail out if the temp directory wasn't created successfully.
if [ ! -e $TMPDIR ]; then
    >&2 echo "Failed to create temp directory"
    exit 1
fi

# Make sure it gets removed even if the script exits abnormally.
trap "exit 1"           HUP INT PIPE QUIT TERM
trap 'rm -rf "$TMPDIR"' EXIT

# Example use of TMPDIR:
for f in *.csv; do
    cp "$f" "$TMPDIR"
    # remove duplicate lines but keep order
    perl -ne 'print if ++$k{$_}==1' "$TMPDIR/$f" > "$f"
done