Speed Up Shell Loops Using Arrays
Just a quick note on addressing a common issue of running redundant commands when using shell loops. Let’s say you needed to get a count of network connections to an Oracle database server for each connection state: established, close_wait, etc. Here’s one way of doing this:
for i in ESTABLISHED CLOSE_WAIT LISTEN IDLE BOUND do echo -e "${i}:\t`netstat -a | egrep "\.152[16].*${i}" | wc -l`" done | column -t
This works just fine, but there is an issue of performance, since you’re running netstat five times. Of course, you can run netstat once, redirect output to a temporary file and then parse the file.
Perhaps an even better option is to use an array to store output of netstat. Note the use of IFS to properly store array values that contain spaces. Also note the printf syntax to output array values one per line.
IFS=$'\n' ; a=($(netstat -a | egrep "\.152[16]")) ; unset IFS for i in ESTABLISHED CLOSE_WAIT LISTEN IDLE BOUND do echo -e "${i}:\t`printf '%s\n' \"${a[@]}\" | grep ${i} | wc -l`" done | column -t