bash 将结果保存到变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15391254/
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-18 04:50:37  来源:igfitidea点击:

save result to variable

bashnetcat

提问by user2129825

How can I save result from nc to the variable?

如何将结果从 nc 保存到变量?

I want:

我想要:

nc: connect to localhost port 1 (tcp) failed: Connection refused

nc:连接到本地主机端口 1 (tcp) 失败:连接被拒绝

on my variable. I tried:

在我的变量上。我试过:

a="$(nc -z -v localhost 1)"
echo $a

but output is empty.

但输出为空。

回答by fedorqui 'SO stop harming'

Just use $()to get the result of the command:

只是$()用来获取命令的结果:

your_var=$(nc -z -v localhost 1)

If you also want the error to be stored, then redirect the 2(error) to 1(normal output):

如果您还希望存储错误,则将2(错误)重定向到1(正常输出):

your_var=$(nc -z -v localhost 1 2>&1)

回答by Micka?l Le Baillif

Just redirect stderrto stdout, expressed by 2>&1:

只需重定向stderrstdout,表示为2>&1

a="$(nc -z -v localhost 1 2>&1)"
echo $a
nc: connect to localhost port 1 (tcp) failed: Connection refused

File descriptor 2is attached (unless redirected) to stderr, and fd 1is attached to stdout. The bashsyntax $( ... )only captures stdout.

文件描述符2附加(除非重定向)到stderrfd 1并附加到stdout。该 bash语法$( ... )仅捕获stdout

回答by Anuj Sethi

-wis your friend in this case

-w在这种情况下是你的朋友

-w timeout Connections which cannot be established or are idle timeout after timeout seconds. The -w flag has no effect on the -l option, i.e. nc will listen forever for a connection, with or without the -w flag. The default is no timeout.

-w timeout 无法建立的连接或在 timeout 秒后空闲超时。-w 标志对 -l 选项没有影响,即 nc 将永远侦听连接,无论是否带有 -w 标志。默认是没有超时。

nc -z -w 3 $serverName $serverPort

Now you can use the $? variable to use it in your script.

现在您可以使用 $? 变量以在脚本中使用它。

if [ $? == 0 ]can be used to use the output of above command in the scripts. Above command will timeout the connection after 3 seconds if it not able to establish.

if [ $? == 0 ]可用于在脚本中使用上述命令的输出。如果无法建立,上述命令将在 3 秒后超时连接。