Reputation: 4479
When I change into a directory with the cd
command, I lose the previous working directory, unless I remember it in my memory. Is there some handy method to go back quickly?
Demo:
$ cd ~/some_path
$ cd /another_path
$ command_to_go_back_to_some_path
Upvotes: 57
Views: 46390
Reputation: 30717
Bash has a shortcut ~-
that expands to the previous working directory, just as ~+
expands to the current working directory:
cd ~-
Although this is more to type than cd -
, this knowledge is useful in other contexts (for example, renaming files with mv foo bar baz ~-
).
Upvotes: 5
Reputation: 4038
If you want to use it in a script and suppress the output, do this:
cd - > /dev/null
Upvotes: 6
Reputation: 52112
For usage in a script, you could use the OLDPWD
shell variable: it contains the previous working directory.
$ pwd
/home/username
$ cd /usr/bin
$ pwd
/usr/bin
$ cd "$OLDPWD"
$ pwd
/home/username
I prefer this over cd -
in scripts because I don't have to suppress any output.
Upvotes: 6
Reputation: 7630
You can also do this
$ pushd ~/some_path
$ pushd /another_path
$ popd
$ popd
Upvotes: 47
Reputation: 454960
As mentioned you can use cd -
. The shell internally does a cd $OLDPWD
.
Upvotes: 29