Reputation: 345
I am writing a bash script which shows me all tcp connections which are important for me. For that I use netstat -atp
. It looks like this:
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
In the bash script I have some of these calls and now I would like to optimize it and call netstat -atp
only once and reuse the results. I tried:
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
After executing the script I always get 0: command not found
as error message. How can I use a variable inside $(...) ?
Thanks!
Upvotes: 1
Views: 108
Reputation: 784958
You can use shell array to store your netstat
command:
# 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
Also note how you can avoid multiple grep
calls by a single awk
call.
Related BASH FAQ: I'm trying to put a command in a variable, but the complex cases always fail!
Upvotes: 1
Reputation: 2721
If you have something like A="foo"
then $("$A")
will be resolved to call the program foo
in the subshell.
So you just have to echo the content of the variable and then grep from it:
num_haproxy_443_timewait=$(echo "$netstat_res" | grep TIME_WAIT ...)
Upvotes: 1
Reputation: 61
At your case, $netstat_res is the result but not the COMMAND, if you want to save the result and use it not only once, save the result to the file is the better way, such as:
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_timewait
Upvotes: 0