user2231715
user2231715

Reputation:

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.

Upvotes: 1

Views: 2823

Answers (3)

fedorqui
fedorqui

Reputation: 289835

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.

Upvotes: 5

glenn jackman
glenn jackman

Reputation: 246867

realpath

parent=$(realpath "$PWD/..")

Upvotes: 0

tue
tue

Reputation: 493

dirname $PWD

or

dirname $(pwd)

Upvotes: 2

Related Questions