Aparichith
Aparichith

Reputation: 1535

exporting name of last but one directory

As explained in this question, we can get name of current working directory. But how to get last but one directory name?

Scenario:

# working directory /etc/usr/abc/xyz.txt 
printf '%s\n' "${PWD##*/}" #prints abc
#i want to print usr
printf '%s\n' "%{PWD##*/-1}" #prints me whole path

Suggest me how to do this.

Thanks in advance.

Upvotes: 1

Views: 171

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80961

Assuming you don't just want to run basename "$(dirname "$PWD")" for some reason and you really want to use expansion for this (note the caveats here) you would want to use.

# Strip the current directory component off.
tmppwd=${PWD%/*}
# Strip all leading directory components off.
echo "${tmppwd##*/}"

But the array expansion trick mentioned in one of the linked comments is clever (though tricky because of other expansion properties like globbing, etc.).

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 754190

The classic way would be:

echo $(basename $(dirname "$PWD"))

The dirname removes the last component of the path; the basename returns the last component of what's left. This has the additional merit of working near the root directory, where variable editing with ${PWD##…} etc does not necessarily work.

Upvotes: 7

Related Questions