How to make `local` capture the exit code?

Declare the local variable before you assign to it:

thing() {
  local output
  output="$(bash "${1##*/}")"
  echo "$?"
}

In my opinion this is also more readable than setting an additional RET variable. YMMV on that, but it works just as you would expect.


#!/bin/bash
thing() {
   local foo=$(asjkdh) ret="$?"
   echo "$ret"
}

This will echo 127, the correct error code for "command not found".

You can use local to define more than one variable. So I just also create the local variable RET to capture the exit code of the subshell before local succeeds and sets $? to zero.