basename

This is used to extract the file name from a full path by removing the directory path and optional suffix. It is commonly used in shell scripting and file handling to work only with the filename instead of the complete path.

  • Used to extract filename from a full path
  • Can remove file extensions (suffix)
  • Helpful in automation and scripting

Syntax of the “basename” command

basename [options] [path] [suffix]
  • Path: Full path of the file or directory.
  • Suffix: Suffix refers to a specific string (usually a file extension) that you want to remove from the end of the filename.

To extract file name with suffix

➜ basename Documents/test/file1.txt
file1.txt

To extract file name without suffix

➜ basename Documents/test/file1.txt .txt
file1

Options for “basename”

  • -a , –multiple: allows to process multiple files or paths at once
➜ basename -a Documents/test/file1.txt Documents/test/file3.txt Documents/test/file2.txt
file1.txt
file3.txt
file2.txt
  • -s, –suffix: removes a specified suffix (like the extension) form filename output
❯ basename -s .txt Documents/test/file1.txt Documents/test/file3.txt Documents/test/file2.txt
file1
file3
file2
  • -z: prints the output separated by a NULL character instead of a neline. It is mainly useful in scripting
    • example below depends on bash prompt setting - one line in this case missing comparing with command without -z
tomas in 🌐 DELL5420 in ~ via  6GiB/22GiB | 1GiB/16GiB
➜ basename Documents/test/file1.txt
file1.txt

tomas in 🌐 DELL5420 in ~ via  6GiB/22GiB | 1GiB/16GiB
➜ basename -z Documents/test/file1.txt
file1.txt
tomas in 🌐 DELL5420 in ~ via  6GiB/22GiB | 1GiB/16GiB
➜