我正在编写一个bash脚本,它显示了对我来说很重要的所有tcp连接。为此,我使用netstat -atp。看起来是这样的:
num_haproxy_443_established=$(netstat -atp | grep ESTABLISHED | grep :https | grep haproxy | wc -l)
printf "\n show ESTABLISHED connections port 443 \n"
printf " %s" $num_haproxy_443_established在bash脚本中,我有一些这样的调用,现在我想优化它,只调用netstat -atp一次并重用结果。我试过:
netstat_res=$(netstat -atp)
num_haproxy_443_timewait=$("$netstat_res" | grep TIME_WAIT | grep :https | grep haproxy | wc -l)
printf " %s" $num_haproxy_443_timewait执行脚本后,我总是得到0: command not found作为错误消息。如何使用$(.)中的变量?
谢谢!
发布于 2017-06-20 09:11:50
如果您有类似于A="foo"的内容,那么$("$A")将被解析为在子subshell中调用程序foo。
因此,您只需回显变量的内容,然后从它返回grep:
num_haproxy_443_timewait=$(echo "$netstat_res" | grep TIME_WAIT ...)发布于 2017-06-20 09:17:10
可以使用shell数组存储netstat命令:
# your netstat command
netstat_res=(netstat -atp)
# then execute it as
num_haproxy_443_timewait=$("${netstat_res[@]}" |
awk '/TIME_WAIT/ && /:TIME_WAIT/ && /haproxy/{++n} END{print n}')
echo $num_haproxy_443_timewait还请注意如何通过单个grep调用避免多个awk调用。
相关常见问题解答:我试图在变量中放置一个命令,但是复杂的情况总是失败的!
发布于 2017-06-20 09:16:08
在您的情况下,$netstat_res是结果,而不是命令,如果您想保存结果并使用它不止一次,将结果保存到文件是更好的方法,如:
netstat -atp > /tmp/netstat_status.txt
num_haproxy_443_timewait=$(cat /tmp/netstat_status.txt | grep TIME_WAIT | grep :https | grep haproxy | wc -l)
printf " %s" $num_haproxy_443_timewaithttps://stackoverflow.com/questions/44648604
复制相似问题