Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 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/bashTMPFILE=$(mktemp /tmp/tmp.XXXXXXXXXX) || exit 1
echo "program output" >> $TMPFILE2、$RANDOM    编程中,随机数是经常要用到的。BASH也提供了这个功能:$RANDOM 变量,返回(0-32767)之间的随机数,它产生的是伪随机数,所以不应该用于加密的密码。#!/bin/bashTMPFILE="/tmp/tmp_$RANDOM"
echo "program output" >> $TMPFILE 3、$$变量    Shell的特殊变量 $$保存当前进程的进程号。可以使用它在我们运行的脚本中创建一个唯一的临时文件,因为该脚本在运行时的进程号是唯一的。
    这种方法在同一个进程中并不能保证多个文件名唯一。但是它可以创建进程相关的临时文件。#!/bin/bashTMPFILE="/tmp/tmp_$$"
echo "program output" >> $TMPFILELinux Shell参数替换 http://www.linuxidc.com/Linux/2013-06/85356.htmShell for参数 http://www.linuxidc.com/Linux/2013-07/87335.htmLinux/Unix Shell 参数传递到SQL脚本 http://www.linuxidc.com/Linux/2013-03/80568.htmShell脚本中参数传递方法介绍 http://www.linuxidc.com/Linux/2012-08/69155.htmShell脚本传递命令行参数 http://www.linuxidc.com/Linux/2012-01/52192.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-07/104510.htm