[bash]临时文件

来源:互联网 发布:安卓proot运行linux 编辑:程序博客网 时间:2024/06/06 17:22

1. 临时文件目录/tmp:

用户可以随时随地利用mktemp命令创建临时文件与/tmp目录,这个目录在每次系统启动时都会被清空,因此里面的文件都是临时使用的(不能永久保存),用完就不管的。

任何账户都有权在/tmp目录下创建临时文件,完整的读写权限全都给创建它的属主,并且其它账户无权访问它。


2. 使用mktemp模板创建临时文件(本地创建):

#!/bin/bash#所谓的模板就是指文件名末尾的6个X#所创建的文件前缀都相同,除了末尾的6个X系统会以一个随机字符串来替换#并且保证在一个目录中不会产生一样的随机字符串#mktemp命令最后会输出创建的文件名,可以看到最后6个X被替换成一个随机字符串了for (( i = 1; i <= 6; i++ ))domktemp test.XXXXXX#不带任何参数默认在当前目录中创建文件donels -l test.*
一个简单的例子:

#!/bin/bashtmpfile=`mktemp test.XXXXXX`echo The script write to temp file $tmpfileexec 3> $tmpfileecho This is the first line >&3echo This is the second line >&3echo This is the third line >&3exec 3>&-echo Done! The contents are:cat $tmpfilerm -f $tmpfile 2>/dev/null#用完随手一删


还有一个值得警醒的例子:对一个文件写完后必须先关掉才能对其读,即在对文件进行读写的时候一定要注意不要读写之间发生冲突!

#!/bin/bashtmpfile=`mktemp tmp.XXXXXX`exec 3>&1#备份exec 1>$tmpfile#写入tmpfileecho xlkjfeecho xxxxxxexec 1>&-#必须先关闭tmpfile才能使用cat读取,否则会因为冲突而系统报错!exec 1>&3#但是关闭后必须还要还原,否则cat不能正常输出到控制台exec 3>&-a#顺便将临时文件描述符3关掉cat $tmpfile#最后可以放心使用cat在控制台上输出


3. -t选项——在/tmp下创建文件:

#!/bin/bashtmpfile=`mktemp -t test.XXXXXX`#-t选项就表示在/tmp目录下创建临时文件echo This is a test file > $tmpfileecho This is the second line of the test >> $tmpfileecho The temp file is located at $tmpfileecho The contents are:cat $tmpfilerm -f $tmpfile

4. -d创建临时目录:

#!/bin/bashtmpdir=`mktemp -d dir.XXXXXX`cd $tmpdirtmpfile1=`mktemp tmp.XXXXXX`tmpfile2=`mktemp tmp.XXXXXX`echo Writing data to dir $tmpdirecho This is a test line for $tmpfile1 > $tmpfile1echo This is a test line for $tmpfile2 > $tmpfile2echo "ls dir"ls ..echo "ls file"lsecho "cat file1"cat $tmpfile1echo "cat file2"cat $tmpfile2

0 0
原创粉丝点击