歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> SHELL中創建臨時文件的方法

SHELL中創建臨時文件的方法

日期:2017/3/1 9:41:58   编辑: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參數替換 http://www.linuxidc.com/Linux/2013-06/85356.htm

Shell for參數 http://www.linuxidc.com/Linux/2013-07/87335.htm

Linux/Unix Shell 參數傳遞到SQL腳本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell腳本中參數傳遞方法介紹 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell腳本傳遞命令行參數 http://www.linuxidc.com/Linux/2012-01/52192.htm

Copyright © Linux教程網 All Rights Reserved