O'Reilly logo

bash Cookbook by Cameron Newham, JP Vossen, Carl Albing

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Secure Temporary Files

Problem

You need to create a temporary file or directory, but are aware of the security implications of using a predictable name.

Solution

The easy and "usually good enough" solution is to just use $RANDOM inline in your script. For example:

	# Make sure $TMP is set to something
	[ -n "$TMP" ] || TMP='/tmp'

	# Make a "good enough" random temp directory
	until [ -n "$temp_dir" -a ! -d "$temp_dir" ]; do
	    temp_dir="/tmp/meaningful_prefix.${RANDOM}${RANDOM}${RANDOM}"
	done
	mkdir -p -m 0700 $temp_dir
	  || { echo "FATAL: Failed to create temp dir '$temp_dir': $?"; exit 100 }
	  # Make a "good enough" random temp file
	  until [ -n "$temp_file" -a ! -e "$temp_file" ]; do
	      temp_file="/tmp/meaningful_prefix.${RANDOM}${RANDOM}${RANDOM}"
	done
	touch $temp_file && chmod 0600 $temp_file
	  || { echo "FATAL: Failed to create temp file '$temp_file': $?"; exit 101 }

Even better, use both a random temporary directory and a random filename!

	# cookbook filename: make_temp

	# Make a "good enough" random temp directory
	until [ -n "$temp_dir" -a ! -d "$temp_dir" ]; do
	    temp_dir="/tmp/meaningful_prefix.${RANDOM}${RANDOM}${RANDOM}"
	donemkdir -p -m 0700 $temp_dir \
	  || { echo "FATAL: Failed to create temp dir '$temp_dir': $?"; exit 100 }

	# Make a "good enough" random temp file in the temp dir
	temp_file="$temp_dir/meaningful_prefix.${RANDOM}${RANDOM}${RANDOM}"
	touch $temp_file && chmod 0600 $temp_file \
	  || { echo "FATAL: Failed to create temp file '$temp_file': $?"; exit 101 }

No matter how you do it, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required