After pushding too many times, I want to clear the whole stack of paths.

How would I popd all the items in the stack?

I'd like to popd without needing to know how many are in the stack?

The bash manual doesn't seem to cover this.

Why do I need to know this? I'm fastidious and to clean out the stack.

  • 1
    BTW, the complete bash manual is over at gnu.org. If you use the all on one page version, it may be easier to find stuff there.
    – jw013
    Feb 9, 2012 at 6:39
  • Ah wish google indexed that one. Thanks @jw013
    – chrisjlee
    Feb 9, 2012 at 7:14

2 Answers 2


dirs -c is what you are looking for.

  • 2
    this does empty the stack, but does not restore the working directory from the stack bottom Mar 23, 2017 at 15:20

In order to both empty the stack and restore the working directory from the stack bottom, either:

  • retrieve that directory from dirs, change to that directory, and than clear the stack:

    cd "$(dirs -l -0)" && dirs -c

    The -l option here will list full paths, to make sure we don't fail if we try to cd into ~, and the -0 retrieves the first entry from the stack bottom.

    @jw013 suggested making this command more robust, by avoiding path expansions:

    pushd -0 && dirs -c
  • or, popd until you encounter an error (which is the status of a popd call when the directory stack is empty):

    while (( $? == 0 )); do popd; done
  • 1
    The first method is exactly what I wanted. The second wouldn't work in my case since I had called pushd a few times, then removed one of the directories in the middle, then popd was failing when I tried to unroll. I needed to jump over all the buggered up stuff in the middle to get back to where I started. Nov 14, 2017 at 18:21
  • right @ChuckWilbur - if you scrambled the dir stack, popd won't save you :) Nov 14, 2017 at 22:51
  • 1
    It's better to pushd -0 instead of cd "$(dirs ...)".
    – jw013
    Dec 7, 2017 at 20:50
  • @jw013 how so? that would mess with the dir stack even more (which we're trying to clear here..) Dec 11, 2017 at 13:56
  • 5
    cd "$(...)" works in 90%, probably even 99% of use cases, but with pushd -0 you can confidently say 100%. There are so many potential gotchas and edge cases associated with expanding file/directory paths in the shell that the most robust thing to do is just avoid it altogether, which pushd -0 does very concisely. There is no chance of getting caught by a bug with a weird edge case if you never take the risk. If you want further reading on the possible headaches involved with Unix file / path names, a good starting point is mywiki.wooledge.org/ParsingLs
    – jw013
    Dec 12, 2017 at 15:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .