1

Does bash support variable substitution in return statement?

From man bash:

return [n]
       Causes a function to stop executing and return the value specified by n to its caller.

Is n allowed to be a variable substitution?

I tested on the following example:

$ cat t345.sh
f()
{
  local x=13
  return $x
}

f
echo $?

$ bash t345.sh
13

$ bash --version
GNU bash, version 5.2.21(1)-release (x86_64-pc-cygwin)

Here we see that Bash doesn't complain about return $x and f returns 13.

Was it linke this all the time OR since which version Bash started supporting this?

1 Answer 1

3

Has always been like this, because Variable substitution is not done on a per-statement basis.

It is not return that expands the variable, much like it's not echo that would expand echo $? – all such expansions are done as one of the input parsing steps before command execution; meaning that they apply equally to most commands (with only a few exceptions). By the time of execution, the command will have already become return 13 (or echo 13) and the individual statements will not need to know anything about variables.

(In fact, it doesn't even distinguish between different parts of the command – you could even have local y=return; $y $x and that would also have the same effect as return 13, which hopefully gets the point across.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .