Is there a subshell created when I run `sh -c “command”`, a new shell or none of these?

后端 未结 7 721
醉话见心
醉话见心 2020-12-08 23:18

In bash, when I run the following command:

sh -c \"command\"

is there created a subshell and then the command

相关标签:
7条回答
  • 2020-12-08 23:22

    Regardless bash

    Running this simple line will show you a lot:

    $ echo $$;sh -c 'echo $$;ps axfw | grep -B2 $$'
    14152
    12352
    14147 ?        S      0:00 xterm
    14152 pts/4    Ss     0:00  \_ bash
    12352 pts/4    S+     0:00      \_ sh -c echo $$;ps axfw | grep -B2 $$
    12353 pts/4    R+     0:00          \_ ps axfw
    12354 pts/4    S+     0:00          \_ grep -B2 12352
    

    This is clearly a child but what's a subshell?

    Well, my current running shell pid is 14152

    $ echo $$ $BASHPID $BASH_SUBSHELL 
    14152 14152 0
    $ (echo $$ $BASHPID $BASH_SUBSHELL)
    14152 12356 1
    $ ( (echo $$ $BASHPID $BASH_SUBSHELL) )
    14152 12357 2
    

    Well nice: BASHPID is a dynamic variable which take alway the value of executing pid:

    $ echo $BASHPID | sed \$a$BASHPID | sed \$a$BASHPID
    12371
    12372
    12373
    

    Hmmm where is my current working pid?

    $ sed "\$a$BASHPID $$" < <(echo "$BASHPID $$"| sed "\$a$BASHPID $$")
    12386 14152
    12387 14152
    14152 14152
    

    Well I've find them!

    $ echo $BASHPID $$;(echo $BASHPID $$;ps axfw | grep -B3 $BASHPID)
    14152 14152
    12469 14152
    14152 pts/4    Ss     0:00  \_ bash
    12469 pts/4    S+     0:00      \_ bash
    12470 pts/4    R+     0:00          \_ ps axfw
    12471 pts/4    S+     0:00          \_ grep -B3 12471
    

    Conclusion

    When you

    $ echo $BASHPID $$ $BASH_SUBSHELL;(echo $BASHPID $$ $BASH_SUBSHELL)
    14152 14152 0
    12509 14152 1
    

    use parenthesis or pipe (|), you will create subshell which is a forked child of a running shell.

    But when you

    $ echo $BASHPID $$ $BASH_SUBSHELL;bash -c 'echo $BASHPID $$ $BASH_SUBSHELL'
    14152 14152 0
    12513 12513 0
    

    You will burn a child, running a shell interpreter, so it's a subshell, but not linked to his parent.

    Nota: If the child is not linked to his parent, they use same I/O files descriptors. So if you close your window (pts/4 in my run), you will send a SIGHUP to all process using them.

    0 讨论(0)
  • 2020-12-08 23:24

    I think that with examples it's possible to understand the situation
    (in my case sh is a symbolic link to /bin/dash).
    I did this tests for sh:

    echo $$ ; sh -c 'echo $$ ; sh -c '"'"'echo $$'"'"' '
    16102
    7569
    7570
    

    Three different PID, three different shell. (If there are different shells, there is not a subshell spawn).


    In a similar way for BASH

    echo $$ $BASHPID, $BASH_SUBSHELL ; bash -c 'echo $$  $BASHPID $BASH_SUBSHELL  ; bash -c '"'"'echo  $$ $BASHPID $BASH_SUBSHELL '"'"' '
    16102 16102, 0
    10337 10337 0
    10338 10338 0
    

    Three different $BASHPID no different $BASH_SUBSHELL (see note below for differences between $$ and $BASHPID).
    If we were in a subshell that do not require to be reinitialized, then $$ and $BASHPID should be different.
    In the same way $BASH_SUBSHELL is not incremented, it is always 0. So 2 clues to say again that no new subshell are spawned, we have only new shells.


    From man bash (4.2.45(1)-release) I report some pertinent parts about when a subshell is spawned:

    1. Each command in a pipeline is executed as a separate process (i.e., in a subshell).

    2. If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

      Commands separated by a ; are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed. ...

    3. ( list ) list is executed in a subshell environment
      { list; } list is simply executed in the current shell environment.

    4. A coprocess is a shell command preceded by the coproc reserved word. A coprocess is executed asynchronously in a subshell...

    5. $ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.

    Notes:

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

    • For the differences between the use of single quote '' an double quote "" you can see this question. Let we remember only that if you write the commands within double quote"" the variables will be evaluated via parameter expansion from the original shell, if extquote is enabled as it is by default from shopt.(cfr. 4.3.2 The shopt builtin in the Bash Reference Manual)

      *extquote* If set, $'string' and $"string" quoting is performed within ${parameter} expansions enclosed in double quotes. This option is enabled by default.

    For further references you may find useful e.g.

    • man bash.
    • The section Shell Expansions of the bash manual.
    • The double quote section or
    • the Parameter Expansion of Shell Command Language as defined in The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004 Edition.
    0 讨论(0)
  • 2020-12-08 23:30

    sh will spawn a subshell. But the subshell id stays the same

    21934 pts/0    Ss     0:00 -bash
    21963 pts/0    S      0:00  \_ /usr/bin/sudo -u root -H /bin/bash -c  export AUDITUSER=ch002854; cd $HOME && exec -a '-bash' /bin/bash
    22031 pts/0    S      0:00      \_ -bash
     2969 pts/0    S      0:00          \_ sleep 1000
     2993 pts/0    S      0:00          \_ sleep 1000
     3726 pts/0    R+     0:00          \_ ps af
    

    With sh -c it will just run the command. This will reinitialize your environment variables and therefore it resets $BASH_SUBSHELL to its default 0.

    # sh -c 'echo $BASHPID, $BASH_SUBSHELL'
    12671, 0
    

    While with `` or () you can create a subshell

    # (echo $BASHPID, $BASH_SUBSHELL)
    13214, 1
    
    0 讨论(0)
  • 2020-12-08 23:40

    I made a check of it as well and no, I don't think it (-c) summons a subshell. If we refer to sh itself, the yes sh is a shell that gets summoned, but not if it's about a subshell within sh itself. We can verify this by running a command like:

    # bash -c 'pstree -p; echo Value of PPID in Callee: $PPID; echo Callee PID: $BASHPID / $$'; echo "Caller PID: $$"
    bash(28860)───bash(17091)───pstree(17092)
    Value of PPID in Callee: 28860
    Callee PID: 17091 / 17091
    Caller PID: 28860
    

    As you can see the called shell (17091) and the caller shell (28860) are both connected directly as child-parent. There's nothing in between them. $BASHPID and $$ are even the same, in which case should be different if you're on a subshell. This just tells that there's no subshell summoned when calling commands with -c.

    There's only one special behavior to this, and that is when summoning a single external binary e.g.:

    # bash -c 'pstree -p'; echo "Caller PID: $$"
    bash(28860)───pstree(17124)
    Caller PID: 28860
    

    There bash saves itself from forking and decided to just directly exec() the only command. You might think that perhaps bash always does that to the last command if the command refers to an external executable binary, but no it doesn't:

    # bash -c 'echo Value of PPID in Callee: $PPID; echo Callee PID: $BASHPID / $$; pstree -p'; echo "Caller PID: $$"
    Value of PPID in Callee: 28860
    Callee PID: 17128 / 17128
    bash(28860)───bash(17128)───pstree(17129)
    Caller PID: 28860
    

    Now about

    echo $BASHPID, $BASH_SUBSHELL

    and

    sh -c "echo $BASHPID, $BASH_SUBSHELL"

    and the results are the same.

    It should be the same if echo $BASHPID, $BASH_SUBSHELL is executed in the same shell since "echo $BASHPID, $BASH_SUBSHELL" is first expanded by the shell that interprets the command before it's passed as an argument to sh. If BASHPID is let's say 28860 and BASH_SUBSHELL 0, then the expanded value of "echo $BASHPID, $BASH_SUBSHELL" is 'echo 28860, 0' in which case the command would actually be sh -c 'echo 28860, 0'. The proper way to this actually is to use a single quote to allow interpretation only within the context of the new called shell: sh -c 'echo $BASHPID, $BASH_SUBSHELL', although I'm not really sure if the command itself would be helpful for testing.

    So basically what I'm saying is that the test echo $BASHPID, $BASH_SUBSHELL + sh -c "echo $BASHPID, $BASH_SUBSHELL" doesn't prove anything if -c summons a subshell or not and that the guy who told you that it could mislead since the variables may be substituted is correct.

    Nevertheless, my own test showed that Bash really doesn't summon a subshell with it (-c).

    0 讨论(0)
  • 2020-12-08 23:41

    Check this:

    $ name=foo
    $ echo $name
    foo
    $ sh -c "echo $name"
    foo
    $ sh -c 'echo $name'
    
    $ 
    

    You need ' in stead of " in your command. Else $name will get evaluated to foo before execution

    And to answer your question, yes, it does create/spawn a new shell.

    0 讨论(0)
  • 2020-12-08 23:45

    In this answer I'm thinking of subshell the same way as I think of a subprocess.

    First off, don't be confused by variable expansion. If you write a variable in double quotes, it will be expanded by the calling shell, not the sh or its -c command. So

    sh -c "echo $$" 
    

    gives you the PID of the invoking shell, because it expands $$ before it invokes sh, whereas

    sh -c 'echo $$' 
    

    gives you the PID of the sh command that has been invoked, because the single quotes tell the invoking shell to pass the string $$ to sh unchanged.

    That said, the general answer to your question is:

    1. The sh command is definitely a subshell, invoked by the parent shell when it sees 'sh'
    2. When you note that the argument to -c is treated by it as a shell script, then you see that you'll get a grand-subshell of the invoked sh, whenever a regular shell script would get one.

    More on item 2: Some shell builtins create subshells; others do not. The sh man page talks about this; check out the "if" builtin, or constucts that use backquotes ``. Usage of pipes also causes subshells. You can also deliberately force a subshell by enclosing commands in parentheses. However, enclosing commands in braces {} does NOT of itself cause a subshell.

    sh is designed to run commands, so in most cases you will have subshells. Notable exceptions are the 'case' builtin, variable assignment, option setting, and the . command.

    0 讨论(0)
提交回复
热议问题