百恒网络
Linux系统中如何创建本地临时文件?
  • 百恒服务
  • APP开发
  • 网页案例
  • 网页知识
  • 关于我们
  • 联系我们
  • Linux系统中如何创建本地临时文件?

    2017-09-15 16:37:55 3826
           Linux系统有特殊的目录,专供临时文件使用。Linux使用/tmp目录来存放不需要永久保留的文件。大多数Linux发行版配置了系统在启动时自动删除/tmp目录的所有文件。

           系统上的任何用户账户都有权限在读写/tmp目录中的文件。这个特性为你提供了一种创建临时文件的简单方法,而且还不用操心清理工作。  

            默认情况下,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命令将其删除。 

           以上就是江西网络公司-百恒网络为大家介绍的关于创建本地临时文件的方法,如果大家还有哪些不太明白的地方,可随时来电和我们联系。此外,百恒网络专业为您提供网站建设、微信开发、APP开发等服务,如有需要,我们随时为您效劳!
    展开分享
    服务
    案例
    首页
    动态
    联系
    咨询