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"
}
                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.
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}"
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With