sh: "local" assignment from command loses exit status

From: Eric van Gyzen <eric_at_vangyzen.net>
Date: Thu, 06 Nov 2014 12:20:30 -0500
Jilles and -current:

In sh, if I use a single statement to declare a local variable and
assign the output of a command to it, the exit status of that command is
lost.  For example:

    should_return_false() {
        local var1=`false`
    }

The function should return non-zero, but it returns zero.  This becomes
especially apparent when using the errexit option (-e flag), since the
shell should exit, but it does not.

Splitting the declaration and assignment into two lines works around the
[suspected] bug.

A more complete example follows.

Cheers,

Eric



#!/bin/sh

returns_false() {
    var1=`false`
}

if returns_false; then
    echo 1:FAIL
else
    echo 1:PASS
fi

should_return_false() {
    local var1=`false`
}

if should_return_false; then
    echo 2:FAIL
else
    echo 2:PASS
fi

workaround_returns_false() {
    local var1
    var1=`false`
}

if workaround_returns_false; then
    echo 3:FAIL
else
    echo 3:PASS
fi

set -o errexit
trap 'echo 4:PASS' EXIT
should_return_false
trap '' EXIT
echo 4:FAIL  # because the shell should have exited
Received on Thu Nov 06 2014 - 16:20:32 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:40:53 UTC