CCCPaste

Bash create temporary file function

################################################################################
# Function:     create_temp_file
# Description:  Creates a temporary file
# Arguments:    $1 :- temporary directory name (required)
# Outputs:      Prints name of the created temporary directory
function create_temp_file {
    local temp_dir="${1:?'create_temp_file requires a 1st argument: temp dir'}"

    local prefix
    prefix=$(basename "${temp_dir}")

    local temp_file="${temp_dir}/${prefix}.${RANDOM}${RANDOM}${RANDOM}"
    if ! touch "${temp_file}" || ! chmod 600 "${temp_file}"; then
        echo "FATAL: Unable to create temp file: ${temp_file}: $?" >&2
        exit 1
    fi
    echo "${temp_file}"
}