LJ Archive

UpFront

Tech Tip

Erik Falor

Issue #177, January 2009

Use netstat to See Internet Connections

Using netstat, you can monitor programs that are making connections to remote hosts:

$ netstat -tpe

The -t flag limits the output to show only TCP connections. The -p flag displays the PID and name of the program making the connection. The -e flag displays extra information, such as the user name under which each program is running.

Tech Tip

David A. Sinck

Issue #177, January 2009

Handle Compressed and Uncompressed Files Uniformly

When looking at log files or other files that are compressed and rotated automatically, it's useful to be able to deal with them in a uniform fashion. The following bash function does that:

function data_source ()
{
 local F=$1

 # strip the gz if it's there
 F=$(echo $F | perl -pe 's/.gz$//')

 if [[ -f $F ]] ; then
  cat $F
 elif [[ -f $F.gz ]] ; then
  nice gunzip -c $F
 fi
}

Now, when you want to process the files, you can use:

for file in * ; do
 data_source $file | ...
done

If you have bzip2 files, just modify the data_source function to check for that also.

Tech Tip

Janos Gyerik

Issue #177, January 2009

Using ps to Monitor Processes

In a previous tech tip, we saw how to use kill to monitor processes. Another option is to use ps. With both methods, you can check $? for success/failure. However, note that kill -0 may return failure even if the process actually exists. This happens when the current user has no permission to the process in question, for example: kill -0 1.

To check for a process silently (with no output), use:

kill -0 PID 2>/dev/null
ps -p PID >/dev/null

LJ Archive