Four fun Unix commands

Unix Insider |  Operating Systems

This
month marks the end of my series on small but useful Unix
commands. I don't mean to suggest that Unix has no other useful commands, it's
just that I've run out of the small ones that I think are fun.

basename

The basename command will strip off the directory portion of a filename path
and return only the filename itself. In the following example, basename is
used to strip the directory path from the filename so it returns simply
file.txt.

$ basename /this/is/a/file.txt
file.txt
$

In the example above, the file and path don't necessarily even exist. The
basename command analyzes the string and takes out the pieces it
estimates to be the directory path. Basically, it leaves the last piece of the
string that doesn't contain a slash (/). It also removes any trailing slash in
order to identify the base portion of the name. In the following listing, the
final slash is removed before evaluating the string and returning the word
file as the "base" for the string.

$ basename /this/is/a/file/
file
$
 

The basename utility is very useful for situations in which files are
replicated across multiple directories. In a hypothetical system, a series of
directories contain the current versions of documents, the newest versions of
documents to replace the current versions, and two earlier versions of the
same documents where they've been replaced. Assuming that the directories
are named new, current, old and oldest, a process is needed to
check the names of all the new documents in the new directory. Any documents with the same
name in the old directory are moved to the oldest directory, any documents
with the same name in the current directory are moved to the old directory,
and finally the new documents are moved to the current directory. Using a
for name loop, the code to do this would look as follows (the listing
is numbered for explanatory purposes):

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Operating SystemsWhite Papers & Webcasts

See more White Papers | Webcasts

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question