Deepak Mourya
Deepak Mourya

Reputation: 430

Can we store "cd .." path in a variable in bash file?

I am new to the bash my use case is to store the one previous directory in to a variable.

Example:

DIR='/local/example/'

How can we add /local/ to any variable like $PREV?

Upvotes: 2

Views: 545

Answers (3)

Raman Sailopal
Raman Sailopal

Reputation: 12867

pwd | awk -F\/ '{ print "/"$(NF-1)"/" }'

Split separate the output of pwd using awk using "/" as the field delimiter/ Print the last but one field appended with "/" and with "/" following.

Upvotes: 0

Shawn
Shawn

Reputation: 52336

You can use dirname to strip the last component from a path:

dir=/local/example
prev=$(dirname "$dir")

sets prev to /local

Upvotes: 2

choroba
choroba

Reputation: 241758

You can use parameter expansion on $PWD which contains the current path:

dir=${PWD%/*}  # Remove everything from the last / forward.

Or, use an external tool like readlink with command substitution:

dir=$(readlink -f ..)

Upvotes: 5

Related Questions