Skip to content
Advertisement

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?

Advertisement

Answer

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 ..)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement