Does variable=$(…) store the command or the result of the command in POSIX sh

前端 未结 3 921
南方客
南方客 2020-12-12 07:54

I was wondering: When I e.g. call

list=$(ps -ax)

is ps -ax executed once and I can read the value multiple times or is the command executed e

3条回答
  •  抹茶落季
    2020-12-12 08:47

    POSIX sh guarantees that the command will not be re-executed, see below.

    Be careful about concluding things about POSIX sh through empirical tests. For example, if you time sleep 60 | true, you'd find that bash, ksh, zsh and dash all take 60 seconds. However, POSIX sh still allows it to finish immediately.


    Spec for $():

    The shell shall expand the command substitution by executing command in a subshell environment (see Shell Execution Environment) and replacing the command substitution (the text of command plus the enclosing "$()" or backquotes) with the standard output of the command.

    and when it's applied:

    When a given simple command is required to be executed [...] the following expansions, assignments, and redirections shall all be performed from the beginning of the command text to the end:

    [...]

    1. Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal prior to assigning the value.

    [...]

    Variable assignments shall be performed as follows:

    If no command name results, variable assignments shall affect the current execution environment.

    Since $() is replaced with the text of the command, and this happens before the variable is assigned, the command is guaranteed not to be re-executed in a conforming POSIX sh implementation.

提交回复
热议问题