Assigning exit code to a shell local variable

local t1=$(exit 1) tells the shell to:

  • run exit 1 in a subshell;
  • store its output (as in, the text it outputs to standard output) in a variable t1, local to the function.

It's thus normal that t1 ends up being empty.

($() is known as command substitution.)

The exit code is always assigned to $?, so you can do

function0()
{
  (exit 1)
  echo "$?"
}

to get the effect you're looking for. You can of course assign $? to another variable:

function0()
{
  (exit 1)
  local t1=$?
  echo "$t1"
}

Exit code was stored in $? variable. Using Command Substitution only capture the output, you should use (...) to create subshell:

#!/bin/bash

func() {
  (exit 1)
  local t1=$?
  printf '%d\n' "$t1"
}

func

In bash this works:

loc(){  local   "x=$(exit "$1"):$?"
        printf  '$%s:\t%d\n' \
                 x "${x##*:}" \? "$?"
}

It has to do with the order of command evaluation and variable assignment. local has a return value all its own - and it is the currently executing command, not the command substitution. The reason things like...

x=$(exit 1); echo "$?"

...can return 1 is because there never is a return in that command except for the subshell run to assign $x's value - so $? doesn't get clobbered as it does in practically every other case in which command substitutions are used.

Anyway, with local it does get clobbered - but if you catch it at just the right time - which is while the expansions are still being evaluated and before local's routines have a chance to clobber it - you can still assign it.

unset x; loc 130; echo "${x-\$x is unset}"

...prints...

$x: 130
$?: 0
$x is unset

You should know though that in many shells you cannot rely upon $? being set mid-evaluation in that way. In fact, that's probably because those shells do not bother re-evaluating at every possible juncture as perhaps bash does - which I would argue is probably better behavior than bash's. Do you really want your interpreter recursively loop-evaluating values which are very likely to be overwritten before ever you have the chance to use them?

Anyway, that's how you can do that.