tags:

views:

68

answers:

4

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?

+4  A: 

Something like this should work:

myvar=`pwd`
# ...
cd $myvar
Lukáš Lalinský
Since he explicitely asks about bash I'd use the alternate syntax: `$(pwd)` as it's easier to read in my opinion.
Joachim Sauer
There is nothing bash-specific about `$(…)`; it can and arguably should be used in all instances
Cirno de Bergerac
@sgm: I didn't know that. Indeed it seems POSIX already defines that, so even less reason to use the old backticks.
Joachim Sauer
+6  A: 
myvar="$PWD"
cd "$myvar"

(Quotes are necessary if your path contains whitespaces.)

digitalarbeiter
`$(pwd)` may be more accurate than `$PWD` (but may sometimes give a different path than you expect).
ephemient
And quotes aren't required in the assignment unless there's whitespace in the *command* -- hence, this works fine: **myvar=$PWD**
NVRAM
A: 

in bash

$ a=$(pwd)
ghostdog74
+2  A: 

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
/
/$
Joachim Sauer
Plus, check out the **cd -** command (with a dash/hyphen), and the **$OLDPWD** auto-variable.
NVRAM
Did not know this one! Thanks