Ross Cournoyer Ross Cournoyer - 1 month ago 10
Bash Question

How to print the name of my current directory's parent directory

I hope I phrased my question clearly. Specifically, it is this:

I would like to use test or perhaps a case statement to determine if a directory name contained in the variable $DIR is either my current directory (.) or it's parent directory (..)

Of course I can echo my current directory (echo $PWD), but what is the simplest way to echo the parent of $PWD?

Thanks.

Answer

You can use ${PWD%/*}:

$ echo $PWD
/home/me/test/t
$ echo ${PWD%/*}
/home/me/test

As the expression ${PWD%/*} is stripping the shortest match of /* from back of $PWD:

From Bash Reference Manual → 3.5.3 Shell Parameter Expansion:

${parameter%word}

The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.