I would like to be able to programmaticly detect when my pushd stack is non-empty, within a bash shell. Is there any way to detect this?

Something akin to $SHLVL would be nice. But so far, the only solution I've found is to wrap pushd and popd with aliases that parse the output of the originals to detect the depth. While that would work, it doesn't feel particularly elegant. (Clearly, the information is stored somewhere in the environment.)

My reason is, I wish to adorn my bash prompt with a pushd depth-count, when this is the case.

2 Answers 2


You can check DIRSTACK length:

$ [[ ${#DIRSTACK[@]} -gt 1 ]] && echo dir stack non-empty

Note that you can not use this method if DIRSTACK is unset.

  • I don't know how I missed that, the first time I grep'd the output of set. But sure enough, there it is. The only problem I see is, even though I'm currently 4 pushd's deep, I currently see DIRSTACK=() Mar 30, 2016 at 4:50
  • 1
    @RyanV.Bissell: You must use dirs to list the content of DIRSTACK or printf '%s\n' "${DIRSTACK[@]}"
    – cuonglm
    Mar 30, 2016 at 4:53
  • What happens if DIRSTACK is unset?
    – Wildcard
    Mar 30, 2016 at 5:04
  • @Wildcard: it lose its special meaning, read bash documentation for more details
    – cuonglm
    Mar 30, 2016 at 5:09
depth=$( ( $(dirs -v | wc -l) -1) )

is another, inferior solution.

  • It will fail if directory name contains newline.
    – cuonglm
    Mar 30, 2016 at 10:26
  • 2
    You're right, I didn't think about that. But I can only wish ill upon those who put newlines in directory names.
    – barksdml
    Mar 30, 2016 at 10:38

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.