UNIX and Linux Command Line Tips and Tricks

Checking if a script is already running

It's often important to exit a script if another instance is already running. File locking can be used for this, but it gets untidy. Here's a simple, yet effective way of checking.

#!/bin/sh

progName=`basename $0`
progPid=$$

# Exit if we are already running
if [ $(ps -ef | grep $progName | grep -v $progPid | wc -l) -gt 1 ]
then
	echo Program is already running. Exiting.
	exit 0
fi

# The rest of the script goes here...

Copying files between servers with SSH and Tar

Copying a file from one server to another is easy enough, but what if you want to maintain file permissions and sym links? "tar" is excellent for this kind of work. Instead of creating an archive file, we can pipe the output of tar across the network, as in this example:

tar cf - /home/doug | ssh clientServerName tar xf -

Piping to a file

SSH is a wonderful toy to pipe output from one server to another, but how do we take piped output and direct it to a file?

Easy - use the "cat" command!

ls | ssh doug@otherServer "cat - >> /tmp/ls_output"

Where has all my space gone?

A common problem. You’re running low on disk space and want to remove a few files. A quick way to see where all that space has gone is to use the "du" command. We can sort this by size, and then analyse it with our favourite text file viewer:


du -k /home/doug | sort -n -k 1,1 > /tmp/du
less /tmp/du