“basename” — Tell Me The Last Bus Stop

Few commands exist in Linux (and other Unix-derivatives) for the sole reason of aiding scripting and writing one-liners. basename is one of the little-known commands in that pack (at least for me). Since working in Linux usually translates to working with files, basename becomes extremely handy when meandering long directory paths to access the files.

basename when given the pathname, trims all of its prefix till the last slash (‘/’) character and returns the resulting string. Its syntax is,

basename string [suffix]
Where, string is a pathname, and
       suffix if specified, basename deletes it from the result.

Examples

basename will retrieve the last name from a pathname ignoring any trailing slashes.

$ basename /home/deepak/projects/web/index.html
index.html

$ basename /home/deepak/projects/web/
web

$ basename /
/

Optionally, basename can be used to remove the end of the base name but not the complete base name.

$ basename /home/deepak/projects/web/index.html .html
index

$ basename /home/deepak/projects/web/index.html ml
index.ht

$ basename /home/deepak/projects/web/index.html index.html
index.html

The -a or --multiple switch allows basename to work on multiple pathname arguments.

$ basename -a /etc/network/interfaces /var/log/auth.log
interfaces
auth.log

The optional suffix doesn’t work if basename is processing multiple files, even if they have common last characters.

$ basename -a /var/log/boot.log /var/log/kern.log
boot.log
kern.log
.log

If there’s a common ending pattern to files, cut can be used to trim the file extension out like so:

$ basename -a /var/log/alternatives.log /var/log/auth.log .log | cut -d '.' -f 1
alternatives
auth

Here the -d stands for delimiter (or separator) which chops the string by ‘.‘, and -f 1 extracts the first field of the resulting sub-string.

In case you haven’t noticed, basename adds a newline character while processing multiple paths. That behavior can be opted out via the -z or --zero switch, which ends each line with NULL instead of newline.
basename-end-with-null
Not so helpful on the terminal, but definitely inside scripts.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s