$$ in a script vs $$ in a subshell

前端 未结 4 1790
既然无缘
既然无缘 2020-12-01 21:43

$$ gives process id of the script process when used in a script, like this:

Example 1

#!/bin/bash
# processid.sh
# print process ids

ps         


        
相关标签:
4条回答
  • 2020-12-01 22:09

    I tried and escaping (to pass the $$ to the subshell) does not work as the subshell inherits the $$ value from the parent bash. The solution to this is to use $BASHPID.

    (echo $$; echo $BASHPID)
    

    prints the PID from the parent shell and from the subshell.

    0 讨论(0)
  • 2020-12-01 22:11

    The replacement takes place in the parent shell; the subshell hasn't been started by the time the substitution takes place.

    0 讨论(0)
  • 2020-12-01 22:13

    A more portable way, linux-only, but also compatible with dash:

    read -r my_pid _ < /proc/self/stat
    echo $my_pid
    
    0 讨论(0)
  • 2020-12-01 22:24

    From the bash manpage:

       $      Expands  to  the  process ID of the shell.  In a () subshell, it
              expands to the process ID of the current  shell,  not  the  sub-
              shell.
    
    0 讨论(0)
提交回复
热议问题