我正在编写一个 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
作为错误消息。如何在 $(...) 中使用变量?
谢谢!
最佳答案
如果你有类似 A="foo"
的东西,那么 $("$A")
将被解析为调用程序 foo
在子 shell 中。
所以你只需要回显变量的内容,然后从中获取:
num_haproxy_443_timewait=$(echo "$netstat_res" | grep TIME_WAIT ...)
关于linux - 在后续的 bash 命令中使用 bash 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44648604/