What is $$ in Bash Shell Script?

The “bash” script is a text file that contains a set of commands to perform the defined process. Each bash script has a unique id stored in the “$$” variable. The “$$” variable stores the current shell’s PID  “process identification number.” The $$ variable is commonly used in scripts to generate unique filenames, create temporary files, and perform other tasks that require a unique identifier for the current process.

This post explains the purpose and working of the “$$” in the bash shell.

  • How to Use the $$ in Bash Shell?
  • Using the “echo” Command
  • Using the “ps” Command

How to Use the $$ in Bash Shell?

The “$$” variable is used in the bash shell to get its value using the built-in “echo” and the “ps(process status)” command line utilities. This section carries out the practical implementation of both these tools for getting the “$$” value, i.e., PID.

Example 1: Using the “echo” Command

This practical example prints the “$$” variable value using the “echo” command in the bash script. 

Create or open a bash script named “sample.sh” in the “nano” text editor:

$ nano sample.sh

Script

#!/bin/bash
echo $$
  • The first line “#!/bin/bash” denote the “Bash Shebang” and instructs the shell to execute the script in the bash shell.
  • The second shows an “echo” statement that has “$$” as a parameter to display the PID of the current shell.

Press “Ctrl+S” to save and “Ctrl+X” to exit the editor.

Make Script Executable

It is compulsory to make the script executable “+x” if it is newly created with the help of the “chmod” command:

$ sudo chmod +x Sample.sh

The command has been executed successfully.

Execute the script and check its output, i.e., current shell PID:

$ ./Sample.sh

The output shows the PID “4286” of the current bash “Sample.sh” script.

Example 2: Using the “ps” Command

The “$$” variable value can also be displayed using the “ps(process status)” command. Check it with an existing “code.sh” bash script.

A “code.sh” bash script is opened in the “nano” editor:

$ nano code.sh

Script

#!/bin/bash
ps -p $$

In the above script, the “ps” command displays the current process information followed by the “-p(PID)” flag:

Save and exit the code.sh script in the text editor.

Run the “code.sh” script:

./code.sh

The output shows the “code.sh” bash script process ID “4410”, terminal type TTY, and its execution time “00(hours):00(minutes):00(seconds)”.

Conclusion

In the Bash shell script, $$ is a special variable that represents the process ID (PID) of the current shell. This means that $$ expands to the PID of the Bash process that is currently executing the script.

The value of the “$$” variable can be checked through the pre-installed “echo” and the “ps(process)” commands. This post has illustrated the objective and working of the $$ in the bash shell script.