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!
netstat_restogrepby$(echo "$netstat_res" | grep TIME_WAIT | grep :https | grep haproxy | wc -l)netstat_res="netstat -atp"it would work but then you'd call netstat every time (not sure why you would want to re-use its results anyway)awkwithprintis probably going to be a cleaner solution or answer. Similar to what @anubhava proposed.