Are there objectively better ways to create temporary files in bash scripts?
I normally just name them whatever comes to my mind, such as tempfile-123, since it will be deleted when the script is over. Is there any disadvantage in doing this other than overwriting a possible tempfile-123 in current folder? Or is there any advantage in creating a temporary file in a more careful way?
The
mktemp(1)man page explains it fairly well:In a script, I invoke mktemp something like
which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.
mktempis not standard, but it does exist on many platforms. The “X”s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than othersBy the way, safe creation of temporary files is important for more than just shell scripting. That’s why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…