Return a string from a function in Bash

Bash allows returning status codes (integers) from functions; however, how can a string be returned?

Returning a string from a function

In Bash, command substitution can be used to capture the stdout of a function.

1
2
3
4
5
6
7
f(){
  local var="test"
  echo $var
}

result=$(f)
echo "f returned $result"

Output

1
f returned test

Returning a string and status from a function

If the standard output and status code need capturing, the example above can be modified to include a return status.

1
2
3
4
5
6
7
8
9
f(){
  local var="test"
  echo $var
  return 10
}

result=$(f)
status=$?
echo "f returned $result with status code $status"

Output

1
f returned test with status code 10