user1519226
user1519226

Reputation: 77

Bash set a variable to cut of other variable

I am trying to set a variable to the last thing in the path, but cant seem to figure out how to do it. Right now, I have this, but it does not work:

path=echo pwd
last=echo $path | rev | cut -d / -f 1 | rev

So for example, if the path was ~/one/two/three, I would want last to be set to three. Right now, whenever I runecho $last, all that is outputted is a blank line.

Can anyone help? Thanks!

Upvotes: 0

Views: 116

Answers (3)

Walter A
Walter A

Reputation: 20032

The variable PWD is already filled, so you can do

last=${PWD##*/}
echo "${last}"

Upvotes: 1

Amit Bhardwaj
Amit Bhardwaj

Reputation: 333

You can also achieve same thing using simple awk command as well like below

last=`echo $PWD | awk -F "/" '{print $NF}'`
echo $last

or using sed to strip the / first and then print the last dir name

last=`echo $PWD | sed 's/\// /g' | awk '{print $NF}'`
echo $last

Upvotes: 0

user2926055
user2926055

Reputation: 1991

What you're asking for is called command substitution:

last=$(pwd | rev | cut -d / -f 1 | rev)
echo "$last"

Upvotes: 1

Related Questions