当在脚本中分配piped命令w/stderr重定向到变量时,csh (tcsh)不明确的输出重定向。

时间:2021-07-17 00:07:06

I'm trying to assign the output of my piped commands to a variable in a csh script.

我试图将我的输出命令的输出分配给一个csh脚本中的变量。

The command is:

的命令是:

set VAR="`ping $1 2>&1 | grep 'unknown' | cut -b 7-13`"

This doesn't want to work, however. I get a vague "Ambiguous output redirect."

然而,这并不是想要工作。我得到一个模糊的“模糊的输出重定向”。

I'm lost, because the command itself works when I type it in terminal, and I can see the text unknown

我迷路了,因为当我在终端输入命令时,命令本身是有效的,我可以看到未知的文本。

2 个解决方案

#1


6  

2>&1 isn't valid csh syntax. This only works for Bourne shells.

>&1不是有效的csh语法。这只适用于伯恩外壳。

To pipe both stdout and stderr, you can use the |& operator.

对于stdout和stderr,可以使用|和操作符。

Also note that ping will run forever by default, you probably want to add a -c option to limit the number of times it runs.

还要注意的是,ping将永远运行在默认状态下,您可能希望添加一个-c选项来限制它运行的次数。

set VAR="`ping localhost -c 5 |& grep 'unknown' | cut -b 7-13`"

#2


2  

If that works interactively, your interactive shell is not csh... which is probably a good thing. Stderr redirection in csh uses just >& but only redirects stderr and stdout together into a file.

如果这是交互式的,您的交互式shell不是csh…这可能是件好事。csh中的Stderr重定向仅使用>&但只将Stderr和stdout重新定向到一个文件中。

See also http://www.faqs.org/faqs/unix-faq/faq/part2/section-9.html

参见http://www.faqs.org/faqs/unix faq/faq/part2/section - 9. - html

If the intent is to figure out whether $1 resolves, ping is the wrong tool anyway. Try

如果意图是想弄清楚$1是否解决,那么ping是错误的工具。试一试

set VAR=`dig +short "$1" || echo unknown`

#1


6  

2>&1 isn't valid csh syntax. This only works for Bourne shells.

>&1不是有效的csh语法。这只适用于伯恩外壳。

To pipe both stdout and stderr, you can use the |& operator.

对于stdout和stderr,可以使用|和操作符。

Also note that ping will run forever by default, you probably want to add a -c option to limit the number of times it runs.

还要注意的是,ping将永远运行在默认状态下,您可能希望添加一个-c选项来限制它运行的次数。

set VAR="`ping localhost -c 5 |& grep 'unknown' | cut -b 7-13`"

#2


2  

If that works interactively, your interactive shell is not csh... which is probably a good thing. Stderr redirection in csh uses just >& but only redirects stderr and stdout together into a file.

如果这是交互式的,您的交互式shell不是csh…这可能是件好事。csh中的Stderr重定向仅使用>&但只将Stderr和stdout重新定向到一个文件中。

See also http://www.faqs.org/faqs/unix-faq/faq/part2/section-9.html

参见http://www.faqs.org/faqs/unix faq/faq/part2/section - 9. - html

If the intent is to figure out whether $1 resolves, ping is the wrong tool anyway. Try

如果意图是想弄清楚$1是否解决,那么ping是错误的工具。试一试

set VAR=`dig +short "$1" || echo unknown`