$BASHPID And $$ differ in some cases

I’m reading “BASH pocket guide of Oreilly”.
It said:

The process ID of the current Bash process.
In some cases, this can differ from $$.

Above explanation , explained $BASHPID variable.

Question: which cases?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

An example is provided in the BASHPID description of the bash manpage:

   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.

Here is an example of a subshell outputting the contents of the variable, along with $$ and the contents of BASHPID outside of the subshell.

$ echo $(echo $BASHPID $$)      $$       $BASHPID
              25680    16920    16920    16920
#             |        |        |        |
#             |        |        |        -- $BASHPID outside of the subshell
#             |        |        -- $$ outside of the subshell
#             |        -- $$ inside of the subshell
#             -- $BASHPID inside of the subshell

Method 2

Subshells. $$ is specified by POSIX and always remains the value of the original shell process. $BASHPID is a Bash-specific variable, and is always the value of the process from which the variable is dereferenced, counting subshells.

 $ f() { printf '%s: %d, %dn' "$1" $$ $BASHPID; };
 $ ${BASH_VERSION+shopt -s lastpipe}; set +m;
 $ f 1 >&2 | f 2
2: 31490, 31490
1: 31490, 32545

I did manage to convince the mksh maintainer to add BASHPID to the most recent version, so it is somewhat portable. It is also possible to implement BASHPID in ksh93 yourself on many platforms.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x