DEV Community

Chris Richmond
Chris Richmond

Posted on

Get the last directory a file with bash

Problem:
You need to get the last directory a file is in,

Solution (one of many I'm sure):
using the full filename "/path/to/file/filename.txt"
dirname /path/to/file/filename.txt

this produces /path/to/file, then we use shell replacement as such:
echo ${INPUT##*/}

which produces
file

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay