I want to get just the name of the parent directory for a file.
Example: When I have
path=/a/b/c/d/file, I want only
d and not
/a/b/c/d (which I get from
dirname $path) as output.
Is there any sophisticated way to do this?
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.Sign up to join this community
basename should be used for this task.
The short answer is
dirname /a/b/c/d/file | xargs basename => d
The first step, getting the
dirname of the path, yields the path of the parent folder, as seen below.
dirname /a/b/c/d/file => /a/b/c/d
The path of the parent folder is then piped to another command with
dirname) don't run on streams and instead just on parametized inputs, you cannot directly pipe the results to
| basename. This however is fixed by
xargs, which turns the stream from the pipe into an input for
This allows the final solution to become
dirname /a/b/c/d/file | xargs basename
Which could also be written as ...
echo '/a/b/c/d/file' | xargs dirname | xargs basename