Bash 函数是否可以将值输出到文件描述符,然后仅将其分配给变量?

Mar*_*cus 2 bash shell stdin stdout file-descriptor

我想模拟 Bash 函数的返回值,我想知道是否可以使用临时文件描述符来传递该值。

换句话说:

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>)
Run Code Online (Sandbox Code Playgroud)

ogu*_*ail 5

是的。但是要让它工作,首先你需要stdout为整个调用和命令替换保存到另一个描述符;重定向文件描述符3到它stdout-所以说什么写它可以captured-,其stdoutstdout整个呼叫。例如:

{ myvalue=$(myfunction 3>&1 1>&4); } 4>&1
Run Code Online (Sandbox Code Playgroud)

不过,每次调用该函数时都执行此操作听起来像很多工作。您最好遵循以下约定:

  • 使用stderr报告错误,警告和调试信息(包括原木和提示)
  • 使用stdout用于示出的结果,
  • 并使用return声明来表示总体成功/失败。