how.wtf

Return a string from a function in Bash

· Thomas Taylor

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.

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

Output

1f 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.

1f(){
2  local var="test"
3  echo $var
4  return 10
5}
6
7result=$(f)
8status=$?
9echo "f returned $result with status code $status"

Output

1f returned test with status code 10

#Bash  

Reply to this post by email ↪