Get the parent directory for a file

Solution 1:

It sounds like you want the basename of the dirname:

$ filepath=/a/b/c/d/file
$ parentname="$(basename "$(dirname "$filepath")")"
$ echo "$parentname"
d

Solution 2:

You can use pwd to get the current working directory, and use parameter expansion to avoid forking it into another (sub)shell.

echo ${PWD##*/}

Edit: proven source

Solution 3:

I think this is a less-resource solution:

 $ filepath=/a/b/c/d/file
 $ echo ${${filepath%/*}##*/}
 d

edit: Sorry, nested expansion isn't possible in bash, but it works in zsh. Bash-version:

 $ filepath=/a/b/c/d/file
 $ path=${filepath%/*}
 $ echo ${path##*/}
 d