Skip to content

The basename command

The basename command prints the last part of a path, the file’s name…

The basename command prints the last part of a path, the file’s name, and can strip a suffix such as .txt.

A practice shell in your browser that behaves like bash on Linux for these commands. Nothing you type leaves the page.

Usage

basename PATH [SUFFIX]
basename -s SUFFIX PATH...

Strip the folders (and a suffix) from a path. Prints the last part of a path: the file’s name. Give a suffix such as .txt to remove that too. It only works on the text you give it; the file doesn’t have to exist.

How to use basename

Get the file name from a path

basename /home/learner/projects/app/main.js
main.js

Remove the extension

basename /home/learner/notes.txt .txt
notes
basename -s .jpg beach.jpg cat.jpg
beach
cat

Options

-s SUFFIX, --suffix=SUFFIXremove SUFFIX from every name (implies -a)
-a, --multipletreat every argument as a path

More examples

basename /home/learner/notes.txt
Notes.txt
notes.txt

Questions about basename

Does the file have to exist?

No. basename and dirname only work on the text of the path.

Every everyday command on one page, to print or keep open: the Linux commands cheat sheet.