1

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.

Community
  • 1
  • 1
Aparichith
  • 1,452
  • 4
  • 20
  • 40

2 Answers2

7

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
4

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.).

Community
  • 1
  • 1
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148