Unix Directory Commands

Ok, I’ve posted way too much about the iPhone, I think a few people might actually be reading and subscribing to my blog. I’m actually getting comments too. Time to nip that in the bud with a post about obscure unix commands.

I was reading a tutorial on setting up an IMAP server and the guy was using the pushd and popd commands. What I love about unix is there are obscure commands on your system that do all sorts of things that you never knew about it.

The commands pushd, popd and dirs are commands which help track and change directories. The basics:
   pushd will push a directory onto a stack,
   popd will pop a directory off the stack,
   dirs will list the directories in the stack

When pushing and popping things on and off the stack, the commands will also change your current directory. Here’s an example, moving around while debugging web stuff:

First I want to add the directories to my stack:

$ pushd /opt/sites/htdocs
$ pushd /var/log/httpd
$ pushd /etc/httpd

You will notice as you push something on the stack, your current directory will also change to what you just pushed on. To see what is on your directory stack:

$ dirs -v
0 /etc/httpd
1 /var/log/httpd
2 /opt/sites/htdocs

Now to move around if you use pushd without any arguments it will swap the top two items in the stack changing your directory to what is now the top item.

$ pushd
$ pwd
/var/log/httpd

You can also use pushd +N and it will change to that position in the stack.

$ dirs -v
0 /var/log/httpd
1 /etc/httpd
2 /opt/sites/htdocs
$ pushd +2
$ pwd
/opt/sites/htdocs
$ dirs -v
0 /opt/sites/htdocs
1 /var/log/httpd
2 /etc/httpd

Use popd to remove items from the list. It supports the same +N syntax, or with no arguments will remove the top item and change your directory to the next. Use dirs -c to clear the directory stack.

I need to play around with them more, it seems useful but I haven’t quite incorporated it into my repertoire yet.

Here are online man page reference for the commands:
   pushd man page
   popd man page
   dirs man page

Post a Comment

Your email is never published nor shared. Required fields are marked *