MeshWorld India LogoMeshWorld.

Linux command: dirname

Listen to ArticleAI Speech
~2 min read narration
100%
Linux command: dirname

The Linux command, dirname strips the last component from a given file name.

The dirname is a built-in command and it will output, the complete directory tree; except for the name of the file.

This article shows the usage of dirname command with example.

It simply strips the last part of a file name(after the last forward-slash /) and gives the remaining part containing the name of the directory where that file is saved.

The dirname command

It can be used to identify paths in the shell scripts.

Syntax

dirname [OPTION] NAME...

Options

  • -z, --zero

    End each output line with NUL, not newline

  • --help

    Exits after displaying the help

  • --version

    Exits after displaying version information

Example 1

dirname /home/meshworld/Documents/IntroToUbuntu.docx
# Output -> /home/meshworld/Documents

dirname /home/meshworld/Music/
# Output -> /home/meshworld/Music

dirname DummiesForLinux.pdf
# Output -> .

Example 2

We can also extract the path info and save the result into another variable.

filePath="/home/meshworld/Pictures/TajMahal.jpg"
directoryPath=$(dirname $filePath)

echo "File path: $filePath"
echo "Directory path: $directoryPath"

Output:

File path: /home/meshworld/Pictures/TajMahal.jpg
Directory path: /home/meshworld/Pictures

Conclusion

The dirname command comes handy when we need to retrieve path, where the file exists.

Hope you like this!

Keep helping and happy 😄 coding

Reader Quality Feedback

Did this technical guide help solve your problem?

Suggest Errata ($0)
Vishnu
Primary Author

Vishnu

Founder & Principal Architect at MeshWorld. Senior engineer and instructor specializing in AI agent systems, scalable web architecture, and modern development workflows.

Explore Author Archive
Compute Fuel & Open Testbed
100% Independent & Verified

Fuel High-Density, Zero-Fluff Engineering Deep-Dives

Every guide on MeshWorld is validated on physical Linux nodes and reproducible testbeds. If this article saved you hours of debugging or unblocked production, consider funding our next cluster run.

Weekly Dispatch

Join MeshWorld Dispatch

Get practical tutorials, system blueprints, and curated AI engineering notes straight to your inbox. No fluff, zero spam.

Zero spam. 1-click unsubscribe anytime.Prefer RSS?
Curated Continuations

Up Next in This Domain.

Browse Full Archive