Question
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:
You will get random value every time. This variable can be use to create unique file name as below demonstration shell:
- demo.sh
- #!/bin/sh
- # Create unique file name
- UNIQUE_FILE_NAME="File_$RANDOM.txt"
- while [ -f "$UNIQUE_FILE_NAME" ];
- do
- UNIQUE_FILE_NAME="File_$RANDOM.txt"
- done
- echo "test" > "$UNIQUE_FILE_NAME"
- echo "File '$UNIQUE_FILE_NAME' is unique!"
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:
- demo2.sh
- #!/bin/sh
- TFILE="/tmp/$(basename $0).$$.tmp"
- ls > $TFILE
- echo "See directory listing in $TFILE"
As name suggest both makes unique temporary filename. Just type mktemp at shell prompt to create it:
Supplement
* Unix Special Variables
沒有留言:
張貼留言