Difference between bash pid and $$

前端 未结 2 1394
自闭症患者
自闭症患者 2020-12-06 04:25

I\'m a bash scripting beginner, and I have a \"homework\" to do. I figured most of the stuff out but there is a part which says that I have to echo the pid of the parent bas

相关标签:
2条回答
  • 2020-12-06 05:10

    It'd be best to get well-acquainted with bash(1):

       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.
       [...]
       BASH_SUBSHELL
              Incremented by one each time a subshell or subshell
              environment is spawned.  The initial value is 0.
    

    $BASHPID was introduced with bash-4.0-alpha. If you run bash --version you can find out what version of bash(1) you're using.

    If you're going to be doing much bash(1) work, you'll also need the following:

    • Greg's bash FAQ
    • TLDP bash reference card
    0 讨论(0)
  • 2020-12-06 05:18

    Looking at documentation on this, it looks like:

    1. $$ means the process ID that the script file is running under. For any given script, when it is run, it will have only one "main" process ID. Regardless of how many subshells you invoke, $$ will always return the first process ID associated with the script. BASHPID will show you the process ID of the current instance of bash, so in a subshell it will be different than the "top level" bash which may have invoked it.
    2. BASH_SUBSHELL indicates the "subshell level" you're in. If you're not in any subshell level, your level is zero. If you start a subshell within your main program, that subshell level is 1. If you start a subshell within that subshell, the level would be 2, and so on.
    3. BASH_SUBSHELL is a variable.
    4. Maybe BASHPID isn't supported by the version of bash you have? I doubt it's a "Mac" problem.
    0 讨论(0)
提交回复
热议问题