sh:我如何避免破坏编号的文件描述符?

Ter*_*ary 7 unix shell redirect file-descriptor sh

当我有

  exec 3>>file               # file descriptor 3 now points to file
  [ $dryrun ] && exec 3>&1   # or possibly to stdout
  echo "running">&3
  exec 3>&-                  # and is now closed
Run Code Online (Sandbox Code Playgroud)

我担心文件描述符3可能指向有问题的函数之外.我怎么处理这个?

  • 有建筑next_available_fd吗?
  • 有没有办法将fd3复制到变量,然后在函数完成后将其复制回来?
    • 在这种情况下,我应该担心线程和并发写入fd3吗?
  • 我在sh,但也许bash/ksh/zsh对此有答案?

Wil*_*ell 1

您可以(使用 bash,我还没有尝试使用其他 shell)执行以下操作,而不是使用 exec 在函数内重定向文件描述符:

富() {
  测试 $dryrun && exec 3>&1
  回显运行>&3
} 3>>文件

富
更多命令

在此设置中,“running”将转到文件或原始 stdout,具体取决于 $dryrun,并且 more_commands 将具有 fd 3,就像调用 foo 之前一样。