使用变量中的文件描述符或文件名进行 Bash 重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4102475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:51:40  来源:igfitidea点击:

Bash redirection with file descriptor or filename in variable

bashredirectfile-descriptor

提问by Milo

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?

我尝试了不同的引号组合,但我一直在创建一个“&1”文件,而不是将其写入标准输出。我该怎么做才能让它按照我想要的方式工作?

回答by Sean

A possibly safer alternative to evalis to dup your destination into a temporary file descriptor using exec(file descriptor 3 in this example):

一个可能更安全的替代方法eval是使用exec(在此示例中为文件描述符 3)将目标复制到临时文件描述符中:

if somecondition; then exec 3> destfile; else exec 3>&1; fi

echo bird >&3

回答by chutz

As of 2015, it is possible to redirect to >&${out}. E.g.,

截至 2015 年,可以重定向到>&${out}. 例如,

exec {out}>&1
echo "bird" 1>&${out}

回答by jabbie

Expounding on Diego's answer. To change where stdout goes conditionally

阐述迭戈的回答。有条件地更改标准输出的位置

if [ someCondition ] ; then
  # all output now goes to $file
  exec 1>$file
fi

echo "bird"

Or create your own file descriptor;

或者创建自己的文件描述符;

if [ someCondition ] ; then
  # 3 points to stdout
  exec 3>&1
else
  # 3 points to a file
  exec 3>$outfile
fi

echo "bird" >&3

Adapted from: csh programming considered harmful- check it out for some more redirection tricks. Or read the bash man page.

改编自:被认为有害的 csh 编程- 查看更多重定向技巧。或者阅读 bash 手册页。

回答by paxdiablo

I'm pretty certain it has to do with the order in which bashprocesses the command line. The following works:

我很确定它与bash处理命令行的顺序有关。以下工作:

export out=\&1
eval "echo bird 1>${out}"

because the variable substitution happens beforethe evaluation.

因为变量替换发生评估之前

回答by Diego Sevilla

Try with eval. It should work by interpreting the value of $outitself:

尝试使用eval. 它应该通过解释$out自身的价值来工作:

out='&1'
eval "echo \"bird\" 1>$out"

Will print birdon the standard output (and to a file if you change out).

将打印bird在标准输出上(如果更改,则打印到文件out)。

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 $outis susbstituted (by means of the double quotes) before the eval is performed.

请注意,您必须小心处理 eval 字符串中的内容。请注意带有内部引号的反斜杠,并且$out在执行 eval 之前替换了变量(通过双引号)。