How to get the PID of current bash shell script
In Category Bash
A special variable “$$” can be used with in a shell script to retrieve self process ID (PID). This is useful for monitoring scripts to store their PID in a file for other maintenance script to identify it. The following script shows how it can be done.
#!/bin/bash # store my PID echo $$ > /var/run/monitor.pid while [ 1 ]; do echo I am monitoring something sleep 5s done
Some scripts use their PID to create unique temporary files along with some fixed prefix. The following example script shows how it is done.
#!/bin/bash TMPFILE=myfile.$$ ls -l > $TMPFILE
However the above method serves basic purpose of creating a unique file name but is not recommended to use. Read the following articles on how to generate unique file names in a bash script.
How to generate random/temporary file name using mcookie command
How to generate temporary file name in bash using RANDOM environment variable
Recent Comments