How to create a temporary file in Shell

Source: Internet
Author: User

Sometimes, we need to create a file to temporarily store some output information. When creating a file, there may be problems with the file name. How to create a unique file name is provided in Linux:


1. mktemp (highly recommended)

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. thetemplate may be any filename with some number of 'xs 'appended to it, for example/tmp/tfile. xxxxxxxxxx. if no template is specifieda default of TMP. xxxxxxxxxx is used and the-T flag is implied (see below ). mktemp [-v] | [-dqtu] [-P Directory] [TEMPLATE]-d make a directory instead of a file. # creating a temporary directory

The following shows how to use mktemp:

#!/bin/bashTMPFILE=$(mktemp /tmp/tmp.XXXXXXXXXX) || exit 1echo "program output" >> $TMPFILE


2. $ random

In programming, random numbers are often used. Bash also provides this function: $ random variable, which returns a random number between (0-32767). It generates a pseudo random number, so it should not be used as an encrypted password.

#!/bin/bashTMPFILE="/tmp/tmp_$RANDOM"echo "program output" >> $TMPFILE


3. $ variable

The special variable $ of shell saves the process Number of the current process. You can use it to create a unique temporary file in the script we run, because the process Number of the script at runtime is unique.

This method does not guarantee that multiple file names are unique in the same process. However, it can create temporary files related to processes.

#!/bin/bashTMPFILE="/tmp/tmp_$$"echo "program output" >> $TMPFILE


This article is from the share your knowledge blog, please be sure to keep this source http://skypegnu1.blog.51cto.com/8991766/1439556

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.