What is the meaning of file name ending with .$$?

Hello Sirs,

I'm trying to understand what does it mean when a file name ends with ".$$"

Like in the below snippet.

 if [ $isnext = n -o $isnext = N ]; then
	cat /tmp/input0.$$ >> $filename

Please help me understand it. Thanks in advance.

Hi, $$ is a variable that contains the process id of the shell. It is used in tmp directories, to make it less likely that one process interferes with a temporary file of another process and that the temporary files do not share the same name.

from the man page:

$$: Expands to the process ID of the shell.  In a () subshell, it expands  to  the process ID of the current shell, not the subshell.
2 Likes

So, if you write to a file containing $$ you are fairly sure (but not guaranteed) to have a unique file.

$ echo "Hello World!" > /tmp/myfile.$$
$ ls -l /tmp/myfile*
-rw-rw-r--. 1 rbatte1 users 48 Jul 22 14:15 /tmp/myfile.22384

Within the same script/shell, you can read the files back again because the $$ will still have the same value.

I hope that this helps.
Robin

1 Like

Thank you for your help guys. I appreciate your valuable time.

A more reliable method (bot still not infallible) would be to create a temporary directory. You can then happily write files there and set a trap to clean up when your script ends. If you have mktemp installed then consider something like this:-

#!/bin/bash

tmpdir=$(mktemp -d) || exit 1                        # Abort script if we cannot do this!
if [ -z "$DEBUG" ]
then
   trap "rm -rf $tmpdir" EXIT
else
   printf "Debug mode\n"
fi

echo "Hello world!" > $workdir/output.file

If the variable DEBUG has a value then the directory is not removed so you can go and have a look afterwards. If you don't set it or set or you actively unset it, then the trap will be switched on and the directory removed at the end to reduce the risk of conflicts later.

If you don't have mktemp then you can just try it using:-

tmpdir=/tmp/tmp.dir.$$
mkdir -m 700 $tmpdir || exit 1                        # Abort script if we cannot do this!
...
...
...

I hope that this helps,
Robin