Getting current path in variable and using it

2020-02-08 10:12发布

问题:

I would like to extract the current path in a variable and use it later on in the script

Something like:

myvar = pwd

Later on:

cd myvar

But my bash skills have rusted over the years.

How would i go on about doing that?

回答1:

myvar="$PWD"
cd "$myvar"

(Quotes are necessary if your path contains whitespaces.)



回答2:

Something like this should work:

myvar=`pwd`
# ...
cd $myvar


回答3:

in bash

$ a=$(pwd)


回答4:

Ind addition to the pwd command and the $PWD environment variable, I'd also suggest you look into pushd/popd:

/$ pushd /usr
/usr /
/usr$ pushd /var/log
/var/log /usr /
/var/log$ popd
/usr /
/usr$ popd
/
/$


回答5:

It worked for me:

currentdir=$(cd -)
printf "Generating content at $currentdir\n"


标签: linux bash