Ethan Zhang
Ethan Zhang

Reputation: 4479

How can I return to the previous working directory quickly in Bash?

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

Answers (6)

Toby Speight
Toby Speight

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

yantaq
yantaq

Reputation: 4038

If you want to use it in a script and suppress the output, do this:

cd - > /dev/null

Upvotes: 6

Benjamin W.
Benjamin W.

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

pizza
pizza

Reputation: 7630

You can also do this

$ pushd ~/some_path
$ pushd /another_path
$ popd 
$ popd

Upvotes: 47

codaddict
codaddict

Reputation: 454960

As mentioned you can use cd -. The shell internally does a cd $OLDPWD.

Upvotes: 29

Darragh Enright
Darragh Enright

Reputation: 14136

You can go back to the last dir with cd -

Upvotes: 133

Related Questions