I am a bit confused about how dirs works. The documentation says:


With no arguments, print the contents of the directory stack. Directories are added to this stack with the pushd command, and removed with the cd or popd commands.

Q1. I never use popd nor pushd, but I noticed that dirskeeps track of the directories where I have been (which to me means, that cd adds, not removes, directories to the stack)

Q.2 After a long session using cd, it's common for dirs to print a long list of directories, but this list prints the most recent directory first and it ends with the last directory, so if I have a long list, the screen scrolls, and I can't easily see the most recent set of directories (which are typically the ones I am most interested in).

How can I print the list of directories in reverse order?

I tried dirs | sort -r, but this does not sort the entries correctly, e.g. I get

20 /foo20/bar
2  /foo2/bar
19 ...

The unsorted originals look like

1 /foo/bar
2 /foo2/bar
3  ...
  • You would be better served showing some actual unsorted data. – JRFerguson Nov 16 '12 at 19:58


Did you enable AUTO_PUSHD?

It can be enabled with setopt autopushd or set -N.

That will be why cd is adding to the directory stack.


I assume you're running dirs -v, not just dirs? (I think -v is required to make it list one per line.)

Why not just dirs -v | head? Or dirs -v | less? (Or dirs | tac as qqx suggests.)


sort by default does sorting based on ASCII values, this will not correctly sort numbers with varying numbers of digits. You can use the -n option to tell it to sort based on a leading numeric value.

dirs -v | sort -nr

Or, since the output of dirs comes already sorted but you just want to get that into reverse order you can use the tac command (that's cat in reverse):

dirs -p | tac

I do cd + and then hit Tab so see and navigate the list of recently visited directories, with the latest one at the top.


if you simply sort -r you are arranging the lines in descending order collating from the first character onward to the end of each line. You need to confine the sort key to the second field if you want an "alphabetic" sort:

dirs | sort -rk2,2

This specifies a (r)everse order sort with the sort (k)ey being field two (2) though field (2). By default, fields are whitespace delimited. If they aren't you can specify the separator with -t.

If on the other hand you truly want to order numerically, do:

dirs | sort -rkn1,1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.