Shell scripting (BASH) : How to create temporary random file name
Various methods exists to create a random temporary file name. This is useful if your application/shell scripting needs temporary unique file names.
Method #1: Use of $RANDOM bash shell variable
1) At shell prompt type command:
# echo $RANDOM
You will get random value every time. This variable can be use to create unique file name as demonstrated by createtempfiles.bash script.
1) Download/view createtempfiles.bash script
2) Save the script to your computer and execute it as follows:
$ chmod +x random1.bash
$ ./random1.bash
Output:
/tmp/0.24101.txt
/tmp/0.28872.txt
/tmp/0.8457.txt
/tmp/0.18006.txt
/tmp/0.29528.txt
Use this method if your script needs more than two temporary files.
Method # 2 Use of $$ variable
This is old and classic method. $$ shell variable returns the current running process this can be use to create unique temporary file as demonstrated in following script:
vi random2.bash
#!/bin/bash # TFILE="/tmp/$(basename $0).$$.tmp" ls > $TFILE echo "See diretory listing in $TFILE"
Save the script and execute as follows:
$ chmod +x random2.bash
$ ./ random2.bash
Use this method if your script needs only ONE temporary file.
Method # 3 Use of mktemp or tempfile utility
As name suggest both makes unique temporary filename. Just type mktemp at shell prompt to create it:
$ mktemp
Output:
/tmp/tmp.IAnO5O
OR
$ tempfile
Output:
/tmp/IAnO5O
Make a unique temporary directory instead of a file using –d option to both of them
$ mktemp –d
$ tempfile –d
Both mktemp or tempfile provides the shell scripts facility to use temporary files in safe manner hence it is highly recommended to use them.
You may also be interested in other helpful articles:
- BASH shell: How to create empty temporary files quickly
- Temporary memory files and shell scripts
- Shell tip: Clear the command history and screen when you log out
- BASH Shell Frequently Asked Questions
- How to keep files safe from accidental overwriting with noclobber under BASH shell
Discussion on This Article:
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: file_names, mktemp_command, temporary_file, tmpfile_command



how can i record the log in the log file in shell script?
like during running whatever the user is seeing, that should be recorded in log file.
Use logger command
createtempfiles.bash is missing… But article is still useful
Artem,
Thanks for the heads up! The post has beeb updated.