Can mktemp fail? I recently wrote a script that ensures that the directory created by mktemp actually exists and starts with /tmp so that when the script wipes out its temporary data at the end, it will not ever run something like "rm -rf /". Using fully-qualified paths for everything is also (not) fun.
In another script I was leery about running rm -f -- /path/foo* so I instead used
because then the glob can't affect find's behaviour in weird ways.
Most likely set -e is enough protection against mktemp failing and the rm -f glob probably would've been just fine, but shell scripting has enough footguns that sometimes I can't help but go overboard with paranoia.
For example, "TMPDIR=/dev/null mktemp -d" will reliably fail.
You shouldn't be validating it starts with "/tmp" though, because on quite a few systems, people set TMPDIR=/var/tmp.
You absolutely should check if mktemp exited nonzero, but if it exited 0, the directory should be safe to use. If you want to be really paranoid, you can check if the output is an empty string too after checking the exit code.
I think you're shying a little too far away from bash's globbing. Yeah, bash has footguns, but using clever workarounds can also be a recipe for creating confusing and error prone code in its own way.
Races and TOCTOUs are generally common problems in most concurrent systems that are not considering atomicity by design (e.g. rdbms). It's just that shell can very easily become concurrent...
The point of mktemp is to use the right location on the current system, which may not be /tmp. If you're going to enforce that tmpdir must be /tmp, you might as well not bother with mktemp and just directly create a file or directory in /tmp.
With the "--" and assuming GNU rm, rm -f -- /path/foo* is safe. If you use a glob pattern that does not match itself, then you will want nullglob:
rm foo.[cC]
will remove a file named literally foo.[Cc] if neither foo.c nor foo.C exist, despite the fact that foo.[Cc] does not match the glob. nullglob is probably a good default for bashscripts, but I don't think it exists in posix.
Wouldn't the glob still have issues with files that contain spaces?
My defensiveness generally takes a sharp upturn when I write scripts that will be run as root or ones that delete data, but I'll admit not trusting mktemp's exit code is probably taking it a bit too far.
In another script I was leery about running rm -f -- /path/foo* so I instead used
because then the glob can't affect find's behaviour in weird ways.Most likely set -e is enough protection against mktemp failing and the rm -f glob probably would've been just fine, but shell scripting has enough footguns that sometimes I can't help but go overboard with paranoia.