开发者

What is '$$' in the bash shell?

开发者 https://www.devze.com 2022-12-15 23:37 出处:网络
I\'m beginner at bash shell programming. Can you tell me about \'$$\' symbols in the bash shell? If I try the f开发者_开发技巧ollowing

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

If I try the f开发者_开发技巧ollowing

#> echo $$

it prints

#>18756

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


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.


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号