What does $$ mean in the shell


I once read that one way to obtain a unique filename in a shell for temp files was to use a double dollar sign ($$). This does produce a number that varies from time to time… but if you call it repeatedly, it returns the same number. (The solution is to just use the time.)

I am curious to know what $$ actually is, and why it would be suggested as a way to generate unique filenames.

Best Solution

$$ is the process ID (PID) in bash. Using $$ is a bad idea, because it will usually create a race condition, and allow your shell-script to be subverted by an attacker. See, for example, all these people who created insecure temporary files and had to issue security advisories.

Instead, use mktemp. The Linux man page for mktemp is excellent. Here's some example code from it:

tempfoo=`basename $0`
TMPFILE=`mktemp -t ${tempfoo}` || exit 1
echo "program output" >> $TMPFILE