Exit code of variable assignment to command substitution in Bash

前端 未结 4 1164
不知归路
不知归路 2020-12-01 04:57

I am confused about what error code the command will return when executing a variable assignment plainly and with command substitution:

a=$(false); echo $?
<         


        
4条回答
  •  独厮守ぢ
    2020-12-01 05:38

    Upon executing a command as $(command) allows the output of the command to replace itself.

    When you say:

    a=$(false)             # false fails; the output of false is stored in the variable a
    

    the output produced by the command false is stored in the variable a. Moreover, the exit code is the same as produced by the command. help false would tell:

    false: false
        Return an unsuccessful result.
    
        Exit Status:
        Always fails.
    

    On the other hand, saying:

    $ false                # Exit code: 1
    $ a=""                 # Exit code: 0
    $ echo $?              # Prints 0
    

    causes the exit code for the assignment to a to be returned which is 0.


    EDIT:

    Quoting from the manual:

    If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed.

    Quoting from BASHFAQ/002:

    How can I store the return value and/or output of a command in a variable?

    ...

    output=$(command)

    status=$?

    The assignment to output has no effect on command's exit status, which is still in $?.

提交回复
热议问题