Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

A replacement for the 'basename' command UNIX
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
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 ;-)
  • Currently 3.60 / 5
  You rated: 4 / 5 (5 votes cast)

A replacement for the 'basename' command | 1 comments | Create New Account
Click here to return to the 'A replacement for the 'basename' command' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
A correction...
Authored by: barrysharp on Dec 26, '01 01:05:36PM

to the FIRST mention of pathname "~/bin/BackupsFullBaseBackup.command"

It should read "~/bin/Backups/FullBaseBackup.command"

[ Reply to This | # ]