使用变量中的文件描述符或文件名进行 Bash 重定向
在我的脚本中,我希望能够根据某些条件写入文件或标准输出。我很好奇为什么这在我的脚本中不起作用:
out=\&1
echo "bird" 1>$out
我尝试了不同的引号组合,但我一直创建一个“&1”文件,而不是将其写入标准输出。我该怎么做才能让它按照我想要的方式工作?
In my script I want to be able to write to either a file or to stdout based on certain conditions. I'm curious as to why this doesn't work in my script:
out=\&1
echo "bird" 1>$out
I tried different combination of quotes, but I keep having a "&1" file created instead of it writing to stdout. What can I do to get this to work how I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
eval
的一个可能更安全的替代方案是使用exec
将目标复制到临时文件描述符中(本例中为文件描述符 3):A possibly safer alternative to
eval
is to dup your destination into a temporary file descriptor usingexec
(file descriptor 3 in this example):自 2015 年起,可以重定向到
>&${out}
。例如,As of 2015, it is possible to redirect to
>&${out}
. E.g.,阐述迭戈的答案。有条件地更改 stdout 的位置
或创建您自己的文件描述符;
改编自:csh 编程被认为有害 - 检查一下更多重定向技巧。或者阅读 bash 手册页。
Expounding on Diego's answer. To change where stdout goes conditionally
Or create your own file descriptor;
Adapted from: csh programming considered harmful - check it out for some more redirection tricks. Or read the bash man page.
我非常确定这与 bash 处理命令行的顺序有关。以下工作有效:
因为变量替换发生在评估之前。
I'm pretty certain it has to do with the order in which
bash
processes the command line. The following works:because the variable substitution happens before the evaluation.
尝试使用
eval
。它应该通过解释$out
本身的值来工作:将在标准输出上打印
bird
(如果更改out
则打印到文件) 。请注意,您必须小心 eval 字符串内部的内容。请注意带有内部引号的反斜杠,并且在执行 eval 之前变量
$out
已被替换(通过双引号)。Try with
eval
. It should work by interpreting the value of$out
itself:Will print
bird
on the standard output (and to a file if you changeout
).Note that you have to be careful with what goes inside the eval string. Note the backslash with the internal quotes, and that the variable
$out
is susbstituted (by means of the double quotes) before the eval is performed.