Advertisement
justin_hanekom

Bash create temporary file function

Mar 16th, 2019
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.70 KB | None | 0 0
  1. ################################################################################
  2. # Function:     create_temp_file
  3. # Description:  Creates a temporary file
  4. # Arguments:    $1 :- temporary directory name (required)
  5. # Outputs:      Prints name of the created temporary directory
  6. function create_temp_file {
  7.     local temp_dir="${1:?'create_temp_file requires a 1st argument: temp dir'}"
  8.  
  9.     local prefix
  10.     prefix=$(basename "${temp_dir}")
  11.  
  12.     local temp_file="${temp_dir}/${prefix}.${RANDOM}${RANDOM}${RANDOM}"
  13.     if ! touch "${temp_file}" || ! chmod 600 "${temp_file}"; then
  14.         echo "FATAL: Unable to create temp file: ${temp_file}: $?" >&2
  15.         exit 1
  16.     fi
  17.     echo "${temp_file}"
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement