[bash]临时文件

1. 临时文件目录/tmp:

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

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


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

#!/bin/bash

#所谓的模板就是指文件名末尾的6个X
#所创建的文件前缀都相同,除了末尾的6个X系统会以一个随机字符串来替换
#并且保证在一个目录中不会产生一样的随机字符串

#mktemp命令最后会输出创建的文件名,可以看到最后6个X被替换成一个随机字符串了
for (( i = 1; i <= 6; i++ ))
do
	mktemp test.XXXXXX	#不带任何参数默认在当前目录中创建文件
done
ls -l test.*
一个简单的例子:

#!/bin/bash

tmpfile=`mktemp test.XXXXXX`

echo The script write to temp file $tmpfile

exec 3> $tmpfile
echo This is the first line >&3
echo This is the second line >&3
echo This is the third line >&3
exec 3>&-

echo Done! The contents are:
cat $tmpfile

rm -f $tmpfile 2>/dev/null	#用完随手一删


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

#!/bin/bash

tmpfile=`mktemp tmp.XXXXXX`

exec 3>&1		#备份
exec 1>$tmpfile

#写入tmpfile
echo xlkjfe
echo xxxxxx

exec 1>&-	#必须先关闭tmpfile才能使用cat读取,否则会因为冲突而系统报错!
exec 1>&3	#但是关闭后必须还要还原,否则cat不能正常输出到控制台
exec 3>&-a	#顺便将临时文件描述符3关掉

cat $tmpfile	#最后可以放心使用cat在控制台上输出


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

#!/bin/bash

tmpfile=`mktemp -t test.XXXXXX`	#-t选项就表示在/tmp目录下创建临时文件

echo This is a test file > $tmpfile
echo This is the second line of the test >> $tmpfile

echo The temp file is located at $tmpfile
echo The contents are:
cat $tmpfile

rm -f $tmpfile

4. -d创建临时目录:

#!/bin/bash

tmpdir=`mktemp -d dir.XXXXXX`
cd $tmpdir
tmpfile1=`mktemp tmp.XXXXXX`
tmpfile2=`mktemp tmp.XXXXXX`

echo Writing data to dir $tmpdir
echo This is a test line for $tmpfile1 > $tmpfile1
echo This is a test line for $tmpfile2 > $tmpfile2

echo "ls dir"
ls ..
echo "ls file"
ls
echo "cat file1"
cat $tmpfile1
echo "cat file2"
cat $tmpfile2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值