localと exit status

ハマったのでメモ.

問題

local宣言とコマンド実行を同時に行うと exit statusが適切に取れない.

function test() {
    local val=$(false)
    echo $?
}

これを実行すると "1"って表示されると思っていたんですが, "0"が表示されて
しまいます.

原因

local自体が exit statusを返すためでした.

$ help local
local: local [option] name[=value] ...
    Define local variables.
    
    Create a local variable called NAME, and give it VALUE.  OPTION can
    be any option accepted by `declare'.
    
    Local variables can only be used within a function; they are visible
    only to the function where they are defined and its children.
    
    Exit Status:
    Returns success unless an invalid option is supplied, a variable
    assignment error occurs, or the shell is not executing a function.

コマンドの exit statusを適切に取得する

そうしたい場合は local宣言と代入は分けて書きましょう

function test() {
    local val
    val=$(false)
    echo $?
}