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吗?您可以(使用 bash,我还没有尝试使用其他 shell)执行以下操作,而不是使用 exec 在函数内重定向文件描述符:
富() {
测试 $dryrun && exec 3>&1
回显运行>&3
} 3>>文件
富
更多命令
在此设置中,“running”将转到文件或原始 stdout,具体取决于 $dryrun,并且 more_commands 将具有 fd 3,就像调用 foo 之前一样。