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 $tmpfile4. -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
本文详细介绍了Linux系统中的临时文件目录/tmp及其使用方法,重点讲解了mktemp命令如何创建临时文件,包括创建过程、使用示例以及注意事项。通过实际操作演示,帮助读者了解如何在Linux环境下高效管理临时文件。
595

被折叠的 条评论
为什么被折叠?



