3 # cdhist - cd replacement with a directory stack like pushd/popd
5 # usage: cd [-l] [-n] [-] [dir]
8 # -l print the cd directory stack, one entry per line
9 # - equivalent to $OLDPWD
10 # -n cd to nth directory in cd directory stack
11 # -s cd to first directory in stack matching (substring) `s'
14 # dir cd to dir and push dir onto the cd directory stack
16 # If the new directory is a directory in the stack and the options selected
17 # it (-n, -s), the new working directory is printed
19 # If the variable CDHISTFILE is set, the cd directory stack is loaded from
20 # and written to $CDHISTFILE every time `cd' is executed.
22 # Note: I got this off the net somewhere; I don't know the original author
42 if [ "$CDHISTFILE" ] && [ -r "$CDHISTFILE" ] # if directory history exists
46 while read -r t
# read directory history file
52 if [ "${CDHIST[0]}" != "$PWD" ] && [ -n "$PWD" ]
54 _cdins
# insert $PWD into cd history
57 cdlen
=${#CDHIST[*]} # number of elements in history
61 if [ "$OLDPWD" = "" ] && ((cdlen
>1))
63 '_cdprint' ${CDHIST[1]}
64 builtin cd ${CDHIST[1]}
71 -l) # _cdprint directory list
76 '_cdprint' "$num ${CDHIST[i]}"
80 -[0-9]|
-[0-9][0-9]) # cd to dir in list
81 if (((i
=${1#-})<cdlen
))
83 '_cdprint' ${CDHIST[i]}
84 builtin cd ${CDHIST[i]}
91 -*) # cd to matched dir in list
98 '_cdprint' ${CDHIST[i]}
99 builtin cd ${CDHIST[i]}
118 _cdins
# insert $PWD into cd history
122 cdlen
=${#CDHIST[*]} # number of elements in history
127 echo ${CDHIST[i]} # update directory history
133 _cdins
() # insert $PWD into cd history
134 { # meant to be called only by cd
139 while (( i
< ${#CDHIST[*]} )) # see if dir is already in list
141 if [ "${CDHIST[$i]}" = "$PWD" ]
148 if (( i
>22 )) # limit max size of list
153 while (((i
=i-1
)>=0)) # bump old dirs in list
155 CDHIST
[i
+1]=${CDHIST[i]}
158 CDHIST
[0]=$PWD # insert new directory in list
162 shopt -s expand_aliases
164 # go to known place before doing anything
167 echo CDHIST
: "${CDHIST[@]}"
168 for dir
in /tmp
/bin
- -2 -l
171 echo CDHIST
: "${CDHIST[@]}"