Linuxopsys
Linuxopsys

@linuxopsys

14 Tweets 3 reads May 04, 2023
The basename command in Linux prints the last element of a file path. This is particularly helpful in bash scripts where you only want the file name from a given file path.
In this thread, we will look at various examples to help us understand the basename command in Linux:
The "basename" function takes a filename and prints the last portion of it. If necessary, it can also remove any subsequent suffixes.
[+] Basename command syntax:
The basename command supports two syntaxes:
$ basename NAME [SUFFIX]
$ basename OPTION... NAME...
basename accepts a filename and prints its last component. It can also remove any trailing suffixes if desired. It is a straightforward command with only a few options.
The simplest example is to print the file name without the leading directories:
$ basename /usr/bin/ls
this will only print the word "ls":
If there are any trailing characters the basename command can get rid of them.
$ basename /usr/share/apps/
$ basename /usr/share/apps
Both of the above commands will produce the same results.
[+] Getting the basename for multiple inputs:
Multiple names may be entered as arguments for the basename command. To accomplish this, issue the command with the -a (--multiple) option and a list of files that are spaced apart.
For example, to get the file names of /bin/ls and /bin/lsd you can run:
$ basename /bin/ls /bin/lsd
[+] Removing a Trailing Suffix
If you want remove any trailing suffix from the file name, pass the suffix as a second argument:
$ basename /bin/systemctl ctl
this will only output the word "system"
In general, this feature is very handy if you want to strip file extensions:
$ basename /etc/resolv.conf .conf
Another approach to getting rid of a trailing suffix is to use the -s (--suffix=SUFFIX) option:.
$ basename -s .conf /etc/resolv.conf .conf
The -s option also make it possible to strip any trailing suffix from multiple names:
$ basename -s .conf /etc/resolv.conf .conf /etc/db.conf
This information should be sufficient to help you understand the Linux basename command.
That's all! Thank you for getting this far. I hope you find this thread useful.
If you found this thread valuable:
1. Toss us a follow for more daily threads on Linux, sysadmin and devops → @linuxopsys
2. Like and RT the first tweet so other Linux folks can find it too.

Loading suggestions...