user2390246
user2390246

Reputation: 291

"dirname: missing operand" despite passing a valid path

What is the proper syntax for piping a path into dirname? Running this code

path="d1/d2/d3/d4/d5/filename.gz"
echo "$path" | cut -d'/' -f3-

as wanted yields

d3/d4/d5/filename.gz

But this code

path="d1/d2/d3/d4/d5/filename.gz"
echo "$path" | cut -d'/' -f3- | dirname

yields

dirname: missing operand

Even though dirname d3/d4/d5/filename.gz gives the desired output of d3/d4/d5.

How can I fix this so that dirname acts properly on the output of the cut command?

Upvotes: 0

Views: 80

Answers (1)

Wiimm
Wiimm

Reputation: 3568

You can do it without calling sub-shells:

#!/bin/bash

path="d1/d2/d3/d4/d5/filename.gz"

# remove first 2 directories:
p2="${path#*/*/}"

# get dirname
dirname="${p2%/*}"

# Special handling if p2 does not contain a slash.
# So it's compatible to tool dirname.
[[ $dirname = "$p2" ]] && dirname=.

# print the result
echo "$dirname"

Upvotes: 1

Related Questions