Using the dirstack in bash

I’m writing this post because its one of the most useful tools in bash and I always forget the syntax. Its hard to Google for and the piece of paper I write it down on always gets lost. And asking my advanced bash friends to remind me often indicates that they are unaware of this feature.

Most intermediate shell users are aware of the dirstack and how to manipulate it using pushd, popd, and dirs. If you aren’t, you really are missing out on something. Check out the basics here: http://www.faqs.org/docs/bashman/bashref_73.html

Once you’ve been using the dirstack for a while, you start to wish you could use those directories in commands. You might want to ls the directory you were in two jumps ago, or cat a file from a previous directory.

It’s easy to do, but I always forget the syntax. So here it is for my (and your) Alzheimered future reference: ~1 through ~9 refer to the last directory, the second last directory, etc on the stack.

For example:

dusty:dir3 $ dirs
~/test/dir3 ~/test/dir2 ~/test/dir1
dusty:dir3 $ ls ~2 # that refers to dir1
dusty:dir3 $ touch ~2/hello
dusty:dir3 $ ls ~2
hello
dusty:dir3 $ dirs
~/test/dir3 ~/test/dir2 ~/test/dir1
dusty:dir3 $ ls
dusty:dir3 $ ls ../dir1 # told you it was dir1
hello

So that’s it. the whole point of this post is to remind me that the syntax is ~1 and not !1 or -1 or $1 or %1 or !$1 or ~$1 or…

Comments are closed.