A replacement for the 'basename' command

Dec 26, '01 10:40:02AM

Contributed by: barrysharp

I've written many unix scripts over the past years and very early on I found myself using the basename command numerous times.

As I'm always concerned about performance I looked into using the powerful shell built-in variable substition feature to reduce my use of basename.

Read the rest of the article to see what I came up with...

Let's say (purely an example to make my point) you invoke a Borne/Korn Shell script using

~/bin/BackupsFullBaseBackup.command
and within this script you wish to log various messages using a functions such as
function logit
{
echo "`basename $0`: $1"
return 0
}
This function uses basename to obtain the base of the path ~/bin/Backups/FullBaseBackup.command which is "FullBaseBackup.command".

Now if you use the following shell substition feature (as soon as the script begins execution) to obtain the calling path's base name, then the basname command can be avoided altogether which will/could save considerable overhead of not having to launch the basename command over and over again each time a log message is issued.
NAME=="${0##*/}"  # Obtain base of the calling pathname
and change function logit to
function logit
{
echo "${NAME}: $1"
return 0
}
On the face of it this may not seem much of a 'trick' or performance improvement -- but if this avoids basename being called hundreds of times each day, month after month, year after year then there's considerable benefit over the long haul.

Process creation (such as launching a basename command) is a very expensive operation in Unix and any reduction in the number of process creations is desirable. If system accounting is enabled then the daily accounting program will have less processes to account for ;-)

Comments (1)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20011226104002713