R0b0tn1k
R0b0tn1k

Reputation: 4306

Getting current path in variable and using it

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?

Upvotes: 40

Views: 87444

Answers (5)

EliuX
EliuX

Reputation: 12685

It worked for me:

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

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308269

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
/
/$

Upvotes: 5

ghostdog74
ghostdog74

Reputation: 343141

in bash

$ a=$(pwd)

Upvotes: 9

digitalarbeiter
digitalarbeiter

Reputation: 2335

myvar="$PWD"
cd "$myvar"

(Quotes are necessary if your path contains whitespaces.)

Upvotes: 75

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41326

Something like this should work:

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

Upvotes: 14

Related Questions