1

I am a Java guy, learning how to write a clean bash script. I am writing a bash function that does some calculations. During the run, this function must log something that shows how the internal calculation goes. Then at the end, it returns the computed value.

This way:

calculate() {
    local some_varible_1
    # doing something here
    printf "result: %s\n" "$some_varible_1"

    local result
    # doing something again
    printf "result: %s\n" "$result"

    # return value
    # the stdout must be cleared somehow
    printf "%s" "$result"
}

The function does not need (and does not have) any input param because it works with script level global variables and I would like to avoid using input param only for passing back the return value.

This is how I call this function:

computed_valuee=$(calculate)

Is that possible to reset the stdout somehow before returning the result from the function? What is the best way to write a bash function that has a return value but the function logs info to stdout as well?

zappee
  • 20,148
  • 14
  • 73
  • 129
  • 4
    What about sending the other messages to `stderr`, instead of `stdout` (`printf ... >&2`)? – Renaud Pacalet Feb 23 '22 at 12:42
  • bash functions (different to Java) don't have a return value; in this respect, the term _function_ is a misnomer. There **is** a `return` statement (which you don't use), but this just sets the exit code (which the caller can query, but you don't in your example). If you don't use an explicit `return` statement, the exit code of the last command is returned. With this in mind, I don't understand your question. In particular, I don't know what _reset the stdout_ means. – user1934428 Feb 23 '22 at 13:11
  • 1
    Does this answer your question? [How do I echo directly on standard output inside a shell function?](https://stackoverflow.com/questions/31656645/how-do-i-echo-directly-on-standard-output-inside-a-shell-function) – pjh Feb 23 '22 at 13:48

0 Answers0