Networking

Unix and Linux network configuration. Multiple network interfaces. Bridged NICs. High-availability network configurations.

Applications

Reviews of latest Unix and Linux software. Helpful tips for application support admins. Automating application support.

Data

Disk partitioning, filesystems, directories, and files. Volume management, logical volumes, HA filesystems. Backups and disaster recovery.

Monitoring

Distributed server monitoring. Server performance and capacity planning. Monitoring applications, network status and user activity.

Commands & Shells

Cool Unix shell commands and options. Command-line tools and application. Things every Unix sysadmin needs to know.

Home » Commands & Shells

Speed Up Shell Loops Using Arrays

Submitted by on June 7, 2016 – 9:02 am

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

 

Print Friendly, PDF & Email

Leave a Reply