Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

zsh

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"
}
like image 207
balki Avatar asked Sep 21 '11 16:09

balki


2 Answers

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.

like image 162
Idelic Avatar answered Oct 04 '22 16:10

Idelic


Do you have the option of modifying the hello() function? If so, then give it an option to store the result in a variable:

#!/bin/bash

hello() {
  local text="hello"

  if [ ${#1} -ne 0 ]; then
    eval "${1}='${text}'"
  else
    echo "${text}"
  fi
}

func () {
  local var     # Scope extends to called functions.
  hello var
  echo "${var} world"
}

And a more compact version of hello():

hello() {
  local text="hello"
  [ ${#1} -ne 0 ]  && eval "${1}='${text}'" || echo "${text}"
}
like image 21
Andrew Vickers Avatar answered Oct 04 '22 17:10

Andrew Vickers