2017年3月29日 星期三

[Linux 文章收集] BASH Shell: HowTo Create Empty Temporary Files Quickly

Source From Here 
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: 
# echo $RANDOM
1545

You will get random value every time. This variable can be use to create unique file name as below demonstration shell: 
- demo.sh 
  1. #!/bin/sh  
  2.   
  3. # Create unique file name  
  4. UNIQUE_FILE_NAME="File_$RANDOM.txt"  
  5. while [ -f "$UNIQUE_FILE_NAME" ];  
  6. do  
  7.     UNIQUE_FILE_NAME="File_$RANDOM.txt"  
  8. done  
  9.   
  10. echo "test" > "$UNIQUE_FILE_NAME"  
  11. echo "File '$UNIQUE_FILE_NAME' is unique!"  
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: 
- demo2.sh 
  1. #!/bin/sh  
  2. TFILE="/tmp/$(basename $0).$$.tmp"  
  3. ls > $TFILE  
  4. echo "See directory listing in $TFILE"  
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 // Create temple file
/tmp/tmp.erRDXG8krH
# test -f /tmp/tmp.erRDXG8krH && echo "Temp file created" // Confirm that the temple file being created
Temp file created

// -d, --directory: create a directory, not a file
# mktemp -d
/tmp/tmp.TfRrhIE4SZ
# test -d /tmp/tmp.TfRrhIE4SZ && echo "Temp dir created" // Confirm that the temple directory being created
Temp dir created
# ls -hl /tmp/

Supplement 
Unix Special Variables

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...