Skip to content
shellhacks.dev
Bash

Get the Directory Part of a Path in Bash Without dirname

Get the directory part of a path in Bash with ${p%/*} instead of dirname. A name with no slash comes back unchanged, which dirname would turn into a dot.

1 min read
Summarize in AI

You have a path in a variable and need its directory, and starting dirname for every line of a long list is wasteful.

Shell
p=/var/log/app.log
echo "expansion: ${p%/*}   dirname: $(dirname "$p")"
p=app.log
echo "expansion: ${p%/*}   dirname: $(dirname "$p")"
p=/app.log
echo "expansion: [${p%/*}]   dirname: $(dirname "$p")"
Text
expansion: /var/log   dirname: /var/log
expansion: app.log   dirname: .
expansion: []   dirname: /

${p%/*} removes the shortest suffix that starts with a slash, which leaves everything before the last component. It is parameter expansion, so no process starts. The output shows where it parts from the dirname utility: with no slash in the value nothing matches and the whole name comes back, and for a file in the root the result is empty where dirname prints a slash.

Use the expansion only when the input is a clean path, and add the two special cases yourself, ${p%/*} followed by a test for an unchanged value, when it is not. A trailing slash also changes the answer, since dirname strips it first and the expansion does not.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.