Moving around in Linux with pushd, popd, and dirs
Often when administering a Linux server, you move around between the same few directories. You cd
here, you cd
there, and then you cd
back here. Instead of cd
‘ing so much, Linux has 3 powerful commands that can help you: pushd
, popd
, and dirs
.
How do these commands work? Linux maintains the concept of a stack of directories, at all times. pushd
, popd
, and dirs
controls this stack.
- To view the stack, type
dirs
pushd dirname
changes directory todirname
, and pushes it onto the head of the stackpopd
changes directory to the directory at the head of the stack, and pops it off
Here’s an example of how I use pushd
, popd
, and dirs
in Ruby on Rails:
$ pwd
~/myapp
$ pushd ./config
~/myapp/config ~/myapp
$ pwd
~/myapp/config
$ vim ./database.yml
$ popd
~/myapp
$ pwd
~/myapp
In this example, I started out in my main Ruby on Rails directory. I cd
’d to ./config
using pushd
. Then I edited the database.yml
file. Finally, I cd
’d back to my main Ruby on Rails directory using popd
.
Finally, although I did not demonstrate it in this example, you can pushd
and popd
many levels deep – the stack is not limited to 1 directory.