Search code examples
bashshellstdoutstdinfile-descriptor

Is it possible for a Bash function, to output a value to a file descriptor, and assign only that to a variable?


I wanted to simulate a return value for a Bash function, and I was wondering if it's possible to use an adhoc file descriptor, in order to pass the value.

In other words:

function myfunction {
  # print `stdout_value` to stdout
  # print `stderr_value` to stderr
  # print `return_value` to FD3 (or other)
}

# the values printed to stderr/stdout should be printed, but only
# `return_value` should be assigned to `myvalue`
myvalue=$(myfunction <FDs manipulation>)

Solution

  • Yes it is. But for that to work, first you need to save stdout to another descriptor for the whole call, and for command substitution; redirect file descriptor 3 to its stdout—so that what's written to it can be captured—, and its stdout to stdout of the whole call. E.g:

    { myvalue=$(myfunction 3>&1 1>&4); } 4>&1
    

    Doing this for each call to that function sounds like a lot of work though. You better follow the convention that:

    • use stderr for reporting errors, warnings and debug info (including logs and prompts),
    • use stdout for showing results,
    • and use a return statement to denote overall success/failure.