bash

How to get return value from a function when the output is assigned to a local variable?


I can get the return value from a function foo without problem such as:

$ cat test.sh
#!/usr/bin/bash
foo()
{
  echo "hello"
  return 20
}

bar()
{
    x=$(foo)
    rc=$?
    echo $rc
}
bar

$ test.sh
20

However, I cannot get the return value when I call function foo when assigning its output to a local variable.

$ cat test2.sh
#!/usr/bin/bash
foo()
{
  echo "hello"
  return 20
}

bar()
{
    local x=$(foo)
    local rc=$?
    echo $rc
}
bar

$ bash t2.sh
0

Is there a way to get around it without losing the local scope declaration?


Solution

  • Make the variable local in one command, then assign to it as a separate command:

    bar()
    {
        local x
        x=$(foo)
        local rc=$?
        echo $rc
    }
    

    Since the assignment is separate from the local declaration, the commands' statuses don't conflict.