tags:

views:

167

answers:

2

I'm beginner at bash shell programming. Can you tell me about '$$' symbols in the bash shell?

If I try the following

#> echo $$

it prints

#>18756

Can you tell me what this symbol is used for and when?

+9  A: 

It's the process id of the bash process itself.

You might use it to track your process over its life - use ps -p to see if it's still running, send it a signal using kill (to pause the process for example), change its priority with renice, and so on.

Process ids are often written to log files, especially when multiple instances of a script run at once, to help track performance or diagnose problems.

Here's the bash documentation outlining special parameters.

BASHPID, mentioned by ghostdog74, was added at version 4.0. Here's an example from Mendel Cooper's Advanced Bash-Scripting Guide that shows the difference between $$ and $BASHPID:

#!/bin/bash4

echo "\$\$ outside of subshell = $$" # 9602
echo "\$BASH_SUBSHELL outside of subshell = $BASH_SUBSHELL" # 0
echo "\$BASHPID outside of subshell = $BASHPID" # 9602
echo

( echo "\$\$ inside of subshell = $$" # 9602
echo "\$BASH_SUBSHELL inside of subshell = $BASH_SUBSHELL" # 1
echo "\$BASHPID inside of subshell = $BASHPID" ) # 9603
# Note that $$ returns PID of parent process.
martin clayton
Or you could link directly to the official Bash documentation: http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters http://www.gnu.org/software/bash/manual/bashref.html#Shell-Variables
ephemient
Good idea - done, thanks.
martin clayton
A: 

if you have bash, a relatively close equivalent is the BASHPID variable. See man bash

  BASHPID
      Expands  to  the  process  id of the current bash process.  This differs from $$ under certain circumstances, such as subshells
      that do not require bash to be re-initialized.
ghostdog74