The Linux and Unix Basename and Dirname Commands with Examples

The Linux and Unix basename command is usefull in some shell scripts. The basename command prints the final component in the file path. It can remove the file extension, and displays only the filename (without extension).

Example of how the basename command works:

$ basename /etc/passwd
passwd
$ basename /etc/cron.d
cron.d

To get rid of the extension, write it in the basename command syntax:

$ basename /etc/cron.d .d
cron

You can also do this:

$ basename /path/to/file_one_two_three
file_one_two_three
$ basename /path/to/file_one_two_three one_two_three
file_
$ basename /path/to/file_one_two_three ile_one_two_three
f

The Linux and Unix dirname command prints a file path with its final component removed. Dirname does not change the current path, only prints a string.

$ dirname /etc/ssh/ssh_config
/etc/ssh

Liked it? Take a second to support Geekster on Patreon!
Tagged with: , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Support LinuxG via Patreon
Support LinuxG.net on Patreon!
Subscribe

  

Subscribe to get the latest Linux news and how to guides directly on your e-mail!