27 November 2015

It is very common to use command substitution in the right hand side of environment variable assignment. One thing worth noting is that the return value of the assignment is the return value of that command. This is quite handy since it enables us to write code some like the below. However, the is not the case when you "local"/"export" variables and assign values to them in the same line since The return status is zero unless 'local' is used outside a function, an invalid NAME is supplied, or NAME is a readonly variable. (info "(bash) Bash Builtins"). That is, the return code of the command has nothing to do with the return code of the whole expression. Run the following code snippet and study the result.

#!/bin/bash

function mytest {
    # OK
    msg=$(touch /dir/not/exists 2>&1) || echo "msg: $msg"

    # OOPS
    local msg1=$(touch /dir/not/exists 2>&1) || echo "msg1: $msg1"

    # OK
    local msg2
    msg2=$(touch /dir/not/exists 2>&1) || echo "msg2: $msg2"

    # OOPS
    export msg3=$(touch /dir/not/exists 2>&1) || echo "msg3: $msg3"

    # OK
    export msg4
    msg4=$(touch /dir/not/exists 2>&1) || echo "msg4: $msg4"
}

mytest


blog comments powered by Disqus