Getting the basename of a file (ex - /usr/file.mp4's basename is file.mp4) and the directory, it is in, is very important especially while writing shell scripts. In this article, we will explore how we can do this using basename and dirname commands. At the same time, I will also mention a few basic applications.
How to find a basename of a file
~$ basename /usr/bin/sort
Output:
sort
Application: It is highly useful in getting the basename of a script it is used in. I use this to write 'helps' in my scripts.
~$ cat time.sh
#!/bin/bash
help_page(){
cat << document
...
example: $(basename "$0") -t 30m 10m
...
document
}
help_page
After executing the above script, we get
...
example: time.sh -t 30m 10m
...
How to get basename of multiple files at once
You can use --multiple
or -a
~$ basename --multiple dir/file1 dir/file2
Output:
file1
file2
You can notice that each output line (in the above example, file1
and file2
) is appended with the newline character (\n
). To remove the \n
, use --zero
or -z
.
[ajay@lenovo ~]$ basename --zero --multiple dir/file1 dir/file2
Output:
file1file2[ajay@lenovo ~]$
How to remove the extension of a file in Linux
You need to append the suffix (i.e. the file extension) next to the file name. Consequently, it will remove the extension along with the directory name.
Syntax:
~$ basename NAME [SUFFIX]
Example:
~$ basename dir/file.mp4 .mp4
Output:
file
Alternatively, you can use --suffix=<your_extension>
as well. Here, -s is the same as --suffix
.
~$ basename --suffix=.mp4 dir/file.mp4
How to find directory of a file using dirname in Linux
Syntax:
~$ dirname [OPTION] NAME...
Example:
~$ dirname '/home/ajay/Documents/Notes/Personal Notebooks'
/home/ajay/Documents/Notes
If NAME contains no /'s, output is '.' meaning the current directory. For example,
~$ dirname file.mp4
Output:
.
Application: dirname is used very often to move in the directory of the script. For example, in my rclone.sh script, I use the following command for rclone's logs.
How to find directories of multiple files
Just use the names of all the files separated by space.
~$ dirname 'dir1/file1' 'dir2/file2'
Output:
dir1
dir2
In the above output, as you can see, the lines are separated by the newline character. Just like basename, to remove the newline character, use --zero
flag.
[ajay@lenovo ~]$ dirname --zero 'dir1/file1' 'dir2/file2'
Output:
dir1dir2[ajay@lenovo ~]$
Conclusion
That's all folks about the basename and dirname. These two commands, although super simple, come very handy while writing shell scripts. If you have any comments, suggestions, problems, or criticism, please mention them below. It will help the community.