创建本地临时文件

默认情况下,mktemp会在本地目录中创建一个文件。要用mktemp命令在本地目录中创建一个临时文件,只要指定一个文件名模板就行了。模板可以包含任意文本文件名,在文件名末尾加上6个X就行了。

$ mktemp testing.XXXXXX 
$ ls -al testing* 
-rw------- 1 rich rich 0 Oct 17 21:30 testing.UfIi13 
$ 

mktemp命令会用6个字符码替换这6个X,从而保证文件名在目录中是唯一的。可以创建多个临时文件,它可以保证每个文件都是唯一的。

$ mktemp testing.XXXXXX 
testing.1DRLuV 
$ mktemp testing.XXXXXX 
testing.lVBtkW 
$ mktemp testing.XXXXXX 
testing.PgqNKG 
$ ls -l testing* 
-rw------- 1 rich rich 0 Oct 17 21:57 testing.1DRLuV 
-rw------- 1 rich rich 0 Oct 17 21:57 testing.PgqNKG 
-rw------- 1 rich rich 0 Oct 17 21:30 testing.UfIi13 
-rw------- 1 rich rich 0 Oct 17 21:57 testing.lVBtkW 
$ 

mktemp命令的输出正是它所创建的文件的名字。在脚本中使用mktemp命令时,可能要将文件名保存到变量中,这样就能在后面的脚本中引用了。

$ cat test19 
#!/bin/bash 
# creating and using a temp file 
tempfile=$(mktemp test19.XXXXXX) 
exec 3>$tempfile 
echo "This script writes to temp file $tempfile" 
echo "This is the first line" >&3 
echo "This is the second line." >&3 
echo "This is the last line." >&3 
exec 3>&- 
echo "Done creating temp file. The contents are:" 
cat $tempfile 
rm -f $tempfile 2> /dev/null 
$ ./test19 
This script writes to temp file test19.vCHoya 
Done creating temp file. The contents are: 
This is the first line 
This is the second line. 
This is the last line. 
$ ls -al test19* 
-rwxr--r-- 1 rich rich 356 Oct 29 22:03 test19* 
$ 

这个脚本用mktemp命令来创建临时文件并将文件名赋给$tempfile变量。接着将这个临时文件作为文件描述符3的输出重定向文件。在将临时文件名显示在STDOUT之后,向临时文件中写入了几行文本,然后关闭了文件描述符。最后,显示出临时文件的内容,并用rm命令将其删除。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值