我用来创建tempfile
,删除它并将其重新创建为目录:
tmpnam=`tempfile`
rm -f $tmpnam
mkdir "$tmpnam"
问题是,如果另一个进程在一个进程X
之后和rm -f X
之前意外执行了临时文件,则该进程可能会获得相同的名称mkdir X
。
答案 0 :(得分:310)
使用mktemp -d
。它创建一个具有随机名称的临时目录,并确保该文件尚不存在。您需要记住在使用它之后删除目录。
答案 1 :(得分:63)
对于更强大的解决方案,我使用类似下面的内容。这样,在脚本退出后,将始终删除临时目录。
清除功能在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
...
来自here的bash脚本目录。
Bash traps。
答案 2 :(得分:56)
我最喜欢的单行是
cd $(mktemp -d)
答案 3 :(得分:5)
以下代码段将安全地创建一个临时目录(-d
),并将其名称存储在TMPDIR
中。 (稍后在代码中显示了TMPDIR
变量的示例用法,该变量用于存储可能会被修改的原始文件。)
在收到任何指定的signals时,第一行trap
将执行exit 1
命令。第二行trap
删除(清除)程序退出时的$TMPDIR
(正常和异常)。在检查mkdir -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
答案 4 :(得分:1)
这里是关于如何使用模板创建临时目录的简单说明。
PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR
TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}
# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH
# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH
# create a tempdir in your systems default tmp path e.g. /tmp
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH
# Do whatever you want with your generated temp dir and var holding its path