Advertisement
justin_hanekom

Bash create temporary directory function

Mar 16th, 2019
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.79 KB | None | 0 0
  1. ################################################################################
  2. # Function:     create_temp_dir
  3. # Description:  Creates a temporary directory
  4. # Arguments:    $1 :- temporary directory name prefix (required)
  5. # Outputs:      Prints name of the created temporary directory
  6. function create_temp_dir {
  7.     local prefix="${1:?'create_temp_dir requires a 1st argument: prefix'}"
  8.     local temp_dir=''
  9.  
  10.     until [[ -n "${temp_dir}" && ! -d "${temp_dir}" ]]; do
  11.         temp_dir="/tmp/${prefix}${RANDOM}${RANDOM}${RANDOM}"
  12.     done
  13.  
  14.     if ! sudo mkdir --parents --mode 0700 "${temp_dir}"; then
  15.         echo "FATAL: Unable to create temp dir: ${temp_dir}: $?" >&2
  16.         exit 1
  17.     fi
  18.     echo "${temp_dir}"
  19.     trap 'rm --force --recursive "${temp_dir}"' ABRT EXIT HUP INT QUIT
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement