2

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

4

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.

4
  • 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=() Commented 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
    Commented Mar 30, 2016 at 4:53
  • What happens if DIRSTACK is unset?
    – Wildcard
    Commented Mar 30, 2016 at 5:04
  • @Wildcard: it lose its special meaning, read bash documentation for more details
    – cuonglm
    Commented Mar 30, 2016 at 5:09
2
depth=$( ( $(dirs -v | wc -l) -1) )

is another, inferior solution.

2
  • It will fail if directory name contains newline.
    – cuonglm
    Commented 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
    Commented Mar 30, 2016 at 10:38

You must log in to answer this question.

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