Sometimes, while working on the command line (especially when dealing with shell scripts), you might be interested in only the filename, but what’s available to you is the complete path of the file. So, the requirement is to strip the directory component of the path. You’ll be glad to know there exists a command – basename – that does this job.
In this tutorial, we’ll be discussing the basics of ‘basename’ using some easy to understand examples. But before we jump on to that, it’s worth mentioning that all examples here have been tested on an Ubuntu 16.04 LTS machine.
Linux basename command
The basename command allows you to strip off components from filenames that aren’t required. Following is the tool’s syntax:
basename NAME [SUFFIX]basename OPTION… NAME…
And here’s what the man page says about it:
basename - strip directory and suffix from filenames
Print NAME with any leading directory components removed. If specified, also remove a trailing
Following are some Q&A-styled examples that should give you a good idea on how the basename command works.
Q1. How does basename command work?
By default, if you run the ‘basename’ command with a full path to a file as an input, the command returns the filename in output. For example, when I executed the following command:
I got the following output:
Q2. Can basename handle multiple inputs?
Yes, it can. But for this to happen, you need to use the -a command line option. For example, when I executed the following command:
basename -a /home/himanshu/Downloads/analytics.pdf /home/himanshu/Pictures/test.png
And here’s the output I got:
Q3. How to make basename strip file extension as well?
Sometimes, you might only want to fetch the filename, but not its extension. Well, this can be done using the -s command line option (which requires you to pass the suffix as input).
For example, the following command:
basename -s .pdf /home/himanshu/Downloads/analytics.pdf
produced this output:
Q4. How to make each line output end with NUL?
By default, the newline character is used as a separator in output. However, if you want, you can force basename to use NUL as the separator. This can be done using the -z command line option.
basename -az /home/himanshu/Downloads/analytics.pdf /home/himanshu/Pictures/test.png
And here’s the output:
So you don’t see the NUL character here. For that, you need to redirect the output to a file, and then open the file in an editor like vim. Here’s what vim showed:
As you can see, basename isn’t a very feature-rich command – the options it provides are limited, and most of those have been discussed here in this tutorial. Once you are done practicing these, head to the tool’s man page to learn more about it.