Bash Scripting echo locally in a function

bashfunctionshell-script

In bash scripts I try to keep my variables local to functions wherever I can and then pass what I need out of functions like bellow

#!/bin/bash

function FUNCTION() {
    local LOCAL="value"
    echo "$LOCAL"   # return this variable
}

GLOBAL=$(FUNCTION)

echo "$GLOBAL"

But is it possible to do this while including the function's own echos so that if the function has it's own messages to output I don't have to catch them in a variable

#!/bin/bash

function FUNCTION() {
    local LOCAL="value"
    echo "$LOCAL"                      # return this variable
    echo "This function is done now"   # do not return this variable
}

GLOBAL=$(FUNCTION)

echo "$GLOBAL"                         # should only echo 'value'

Best Answer

Anything that's printed by the function can be captured if you capture the right output stream. So the easiest way to print something and save some other output is to redirect the superfluous output to standard error:

function FUNCTION() {
    local LOCAL="value"
    echo "$LOCAL"
    echo "This function is done now" >&2
}

Another possibility is to log to a file rather than printing log messages directly, for example using something like this:

log() {
    printf '%s\n' "$@" > my.log
}

That said, Bash functions cannot return variables. The only actual "return" value is the exit code. For this reason (and many others), if you want reliable logging, return values, exception handling and more you'll want to use a different language like Python, Ruby or Java.

Related Question