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

后端 未结 7 722
醉话见心
醉话见心 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:46

    I would say not.

    A subshell is typically reserved for any instance where the shell process needs to perform an operation in an isolated environment, but with access to (a copy of) the current state of the shell, including all global and local variables.

    Examples:

    • Pipelines: echo x | read y
    • Command substitution: line=$( read < file && echo "$REPLY" )

    In most cases, this would result in the shell process forking itself.

    In recent updates of ksh93, some subshells may not actually fork a new process.

    The crux of the matter is that a subshell is always created implicitly.

    Running sh -c ... will create a new shell process, which will discard most of the state and start from scratch. That means that normal (local, global) shell variables are gone. Naturally, the new shell will have a copy of all exported variables.


    A different interpretation of the question could be Does the -c option fork a new process for running ...? Answer: No. It doesn't. However, certain commands passed into the -c argument may require the shell to spawn a subshell, just as when they'd be part of a script, or typed interactively.

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