Search code examples
bashfunctionreturnecho

Clearing the echo history


I have a bash script that calls a function which returns a value. I have included the scripts below:

Script

source ./utilities/function1.sh
result=$(Function1)
echo "Result: $result"

Function1

function Function1 {
    echo "Inside Function: Function1"

cat <<EOF
this is the result
EOF
}

I want to be able to echo to the console within the function and return only the value I want, not including the messages that were echoed to the console, but when I run the script the following is returned:

Result: Inside Function: Func1
this is the result

Is this the best way to return a value from a bash function or is there a way I can echo to the console and return a value without the content of the echo commands from the function?

Thanks in advance


Solution

  • There are a few ways to do what you want. two simple ones are:

    Use STDERR to echo to the console and capture STDOUT in your script. By default, STDOUT is on File Descriptor 1 and STDERR is on File Descriptor 2:

    function myFunction() {
      echo "This goes to STDOUT" >&1  # '>&1' is the default, so can be left out.
      echo "This goes to STDERR" >&2
    }
    
    result=$(myFunction)
    echo ${result}
    

    Use a variable to return a string to the caller:

    function myFunction() {
      echo "This goes to STDOUT"
      result="This goes into the variable"
    }
    
    declare    result="" # Has global scope. Can be modified from anywhere.
    myFunction
    echo ${result}
    

    Global scope variables are not good programming practice, but are a necessary evil in bash scripting.