SHELL中创建临时文件的方法


有时候,我们需要创建文件临时存放一些输出的信息,创建文件时就可能出现文件名存在的问题。如何创建唯一的文件名,Linux为我们提供几个方案:

1、mktemp(强烈推荐)

The  mktemp  utility takes the given filename template and overwrites a portion of it to create a unique filename.  The template  may  be  any filename  with  some  number  of  'Xs'  appended  to  it,  for  example /tmp/tfile.XXXXXXXXXX.  If  no  template  is  specified a  default  of tmp.XXXXXXXXXX is used and the -t flag is implied (see below).

mktemp [-V] | [-dqtu] [-p directory] [template]
-d    Make a directory instead of a file.    # 创建临时目录

下面演示一下 mktemp 如何使用:

#!/bin/bash

TMPFILE=$(mktemp /tmp/tmp.XXXXXXXXXX) || exit 1
echo "program output" >> $TMPFILE

2、$RANDOM

    编程中,随机数是经常要用到的。BASH也提供了这个功能:$RANDOM 变量,返回(0-32767)之间的随机数,它产生的是伪随机数,所以不应该用于加密的密码。

#!/bin/bash

TMPFILE="/tmp/tmp_$RANDOM"
echo "program output" >> $TMPFILE

 

3、$$变量

    Shell的特殊变量 $$保存当前进程的进程号。可以使用它在我们运行的脚本中创建一个唯一的临时文件,因为该脚本在运行时的进程号是唯一的。


    这种方法在同一个进程中并不能保证多个文件名唯一。但是它可以创建进程相关的临时文件。

#!/bin/bash

TMPFILE="/tmp/tmp_$$"
echo "program output" >> $TMPFILE

Linux Shell参数替换

Shell for参数

Linux/Unix Shell 参数传递到SQL脚本

Shell脚本中参数传递方法介绍

Shell脚本传递命令行参数

本文永久更新链接地址:

相关内容