Search code examples
bashshellzsh

How to get the output of a shell function without forking a sub shell?


I have the following functions.

hello () {
        echo "Hello"
}
func () {
        hello
        echo "world"
}

If I don't want the output of the hello function to be printed but want to do something with it, I want to capture the output in some variable, Is the only possible way is to fork a subshell like below? Is it not an unnecessary creation of a new child process? Can this be optimized?

func () {
        local Var=$(hello)
        echo "${Var/e/E} world"
}

Solution

  • An ugly solution is to temporarily replace echo so that it sets a global variable, which you can access from your function:

    func () {
      echo () {
        result="$@"
      }
      result=
      hello
      unset -f echo
      echo "Result is $result"
    }
    

    I agree it's nasty, but avoids the subshell.