【shell实战之】使用临时文件_创建本地临时文件

使用临时文件_创建本地临时文件

#!/bin/bash
# linux系统有一个专供临时文件使用的特殊目录/tmp,系统中任何用户都有权限读写。
# mktemp命令:可以直接在/tmp目录中创建唯一的临时文件。其他用户无法访问。
echo "mktemp命令会任意将6个X替换为同等数量的字符,保证文件名在目录中是唯一的。"

mktemp testing.XXXXXX
mktemp testing.XXXXXX
mktemp testing.XXXXXX
echo "ls -al testing*"
ls -al testing*

echo "脚本中使用mktemp命令时,可以将文件名保存到变量中,可以在随后的脚本中引用"
# creating and usinig 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:"
echo "cat $tempfile"
cat $tempfile
rm -f $tempfile 2> /dev/null

运行结果

mktemp命令会任意将6个X替换为同等数量的字符,保证文件名在目录中是唯一的。
testing.BmFHdU
testing.h3OrJh
testing.lihV6L
ls -al testing*
-rw------- 1 root root 0 Jul 24 21:32 testing.BmFHdU
-rw------- 1 root root 0 Jul 24 21:32 testing.h3OrJh
-rw------- 1 root root 0 Jul 24 21:32 testing.lihV6L
脚本中使用mktemp命令时,可以将文件名保存到变量中,可以在随后的脚本中引用
this script writes to temp file test19.lQEBX8
done creating temp file. the contents are:
cat test19.lQEBX8
this is the first line
this is the second line
this is the last line.

ll命令结果

total 12
drwxr-xr-x  2 root root 4096 Jul 24 21:32 ./
drwxr-xr-x 42 root root 4096 Jul 24 21:14 ../
-rwxrwxrwx  1 root root  944 Jul 24 21:32 create_temp_file.sh*
-rw-------  1 root root    0 Jul 24 21:32 testing.BmFHdU
-rw-------  1 root root    0 Jul 24 21:32 testing.h3OrJh
-rw-------  1 root root    0 Jul 24 21:32 testing.lihV6L
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值