Rohan Gala
Rohan Gala

Reputation: 651

Using a variable to change directory

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

Something like:

mypath="$pwd"

Later on:

cd "$mypath"

But I am getting a different directory when doing ls

Upvotes: 3

Views: 67

Answers (1)

Jens
Jens

Reputation: 72619

Almost:

 mypath=$PWD

This one saves a fork over mypath=$(pwd). While some consider it good practice to always double quote variable assignments, technically it is not needed here, since the shell does not perform word-splitting for variable assignments.

PS: Note that you are assigning to mypath and then use myvar... you should be consistent in your variable naming, otherwise it won't work.

Upvotes: 3

Related Questions