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