How do you use PIPESTATUS, tee and /bin/sh together?

Solution 1:

You solve it by not using sh.

The PIPESTATUS variable specifically, and the ${var[idx]} array syntax in general, are features specific to the Bash shell. They do not exist in POSIX sh, and even shells that do have arrays might use a different syntax.

It just happens that some Linux distributions symlink their /bin/sh to Bash. Other distributions, however, symlink it to dash, Debian Almquist Shell. Both are compatible with POSIX sh scripts, but only Bash accepts the ${PIPESTATUS[…]} syntax.

So if you want to use it, run bash -c "…" instead.

Solution 2:

Workaound for '/bin/sh' or busybox

status=0
eval ` { ls /dontexists || echo status="$?"; } | tee /dev/null`
echo "# status=${status}"

Trace :

busybox sh ~/bin/test.sh 
+ status=0
+ ls /dontexists
+ tee /dev/null
ls: /dontexists: No such file or directory
+ echo status=1
+ eval status=1
+ status=1
+ echo # status=1
# status=1