jkitzmiller
jkitzmiller

Reputation: 37

Isolating the name of the final directory in a path?

I have a variable that contains a file path, like so:

/var/lib/tomcat7/webapps/bender/

What I need to do is create another variable and set it to the value of the final directory (bender), without the trailing slash. How can I make that happen?

Upvotes: 0

Views: 44

Answers (2)

Navaneeth Krishnan M
Navaneeth Krishnan M

Reputation: 141

An alternate way; with regex; just for kicks :)

[[ '/var/lib/tomcat7/webapps/bender/' =~ .*\/(.*)\/ ]] && echo ${BASH_REMATCH[1]}

Upvotes: 0

ruakh
ruakh

Reputation: 183436

You can use the standard basename utility:

my_new_variable="$(basename /var/lib/tomcat7/webapps/bender/)"

(Despite the phrase "non-directory portion" in the first line of the documentation, it will indeed return bender.)

Upvotes: 2

Related Questions