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.
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
--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
-d stands for delimiter (or separator) which chops the string by ‘
-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
--zero switch, which ends each line with NULL instead of newline.
Not so helpful on the terminal, but definitely inside scripts.