Exit code of variable assignment to command substitution in Bash

前端 未结 4 1186
不知归路
不知归路 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:32

    Note that this isn't the case when combined with local, as in local variable="$(command)". That form will exit successfully even if command failed.

    Take this Bash script for example:

    #!/bin/bash
    
    function funWithLocalAndAssignmentTogether() {
        local output="$(echo "Doing some stuff.";exit 1)"
        local exitCode=$?
        echo "output: $output"
        echo "exitCode: $exitCode"
    }
    
    function funWithLocalAndAssignmentSeparate() {
        local output
        output="$(echo "Doing some stuff.";exit 1)"
        local exitCode=$?
        echo "output: $output"
        echo "exitCode: $exitCode"
    }
    
    funWithLocalAndAssignmentTogether
    funWithLocalAndAssignmentSeparate
    

    Here is the output of this:

    nick.parry@nparry-laptop1:~$ ./tmp.sh 
    output: Doing some stuff.
    exitCode: 0
    output: Doing some stuff.
    exitCode: 1
    

    This is because local is actually a builtin command, and a command like local variable="$(command)" calls local after substituting the output of command. So you get the exit status from local.

提交回复
热议问题