1name: cd-history
2description:
3	Test someone's CD history package (uses arrays)
4# Fails on OS/2, since directory names are prepended with drive letter.
5category: !os:os2
6stdin:
7	# go to known place before doing anything
8	cd /
9	
10	alias cd=_cd
11	function _cd
12	{
13		typeset -i cdlen i
14		typeset t
15	
16		if [ $# -eq 0 ]
17		then
18			set -- $HOME
19		fi
20	
21		if [ "$CDHISTFILE" -a -r "$CDHISTFILE" ] # if directory history exists
22		then
23			typeset CDHIST
24			i=-1
25			while read -r t			# read directory history file
26			do
27				CDHIST[i=i+1]=$t
28			done <$CDHISTFILE
29		fi
30	
31		if [ "${CDHIST[0]}" != "$PWD" -a "$PWD" != "" ]
32		then
33			_cdins				# insert $PWD into cd history
34		fi
35	
36		cdlen=${#CDHIST[*]}			# number of elements in history
37	
38		case "$@" in
39		-)					# cd to new dir
40			if [ "$OLDPWD" = "" ] && ((cdlen>1))
41			then
42				'print' ${CDHIST[1]}
43				'cd' ${CDHIST[1]}
44				_pwd
45			else
46				'cd' $@
47				_pwd
48			fi
49			;;
50		-l)					# print directory list
51			typeset -R3 num
52			((i=cdlen))
53			while (((i=i-1)>=0))
54			do
55				num=$i
56				'print' "$num ${CDHIST[i]}"
57			done
58			return
59			;;
60		-[0-9]|-[0-9][0-9])			# cd to dir in list
61			if (((i=${1#-})<cdlen))
62			then
63				'print' ${CDHIST[i]}
64				'cd' ${CDHIST[i]}
65				_pwd
66			else
67				'cd' $@
68				_pwd
69			fi
70			;;
71		-*)					# cd to matched dir in list
72			t=${1#-}
73			i=1
74			while ((i<cdlen))
75			do
76				case ${CDHIST[i]} in
77				*$t*)
78					'print' ${CDHIST[i]}
79					'cd' ${CDHIST[i]}
80					_pwd
81					break
82					;;
83				esac
84				((i=i+1))
85			done
86			if ((i>=cdlen))
87			then
88				'cd' $@
89				_pwd
90			fi
91			;;
92		*)					# cd to new dir
93			'cd' $@
94			_pwd
95			;;
96		esac
97	
98		_cdins					# insert $PWD into cd history
99	
100		if [ "$CDHISTFILE" ]
101		then
102			cdlen=${#CDHIST[*]}		# number of elements in history
103	
104			i=0
105			while ((i<cdlen))
106			do
107				'print' -r ${CDHIST[i]}	# update directory history
108				((i=i+1))
109			done >$CDHISTFILE
110		fi
111	}
112	
113	function _cdins					# insert $PWD into cd history
114	{						# meant to be called only by _cd
115		typeset -i i
116	
117		((i=0))
118		while ((i<${#CDHIST[*]}))		# see if dir is already in list
119		do
120			if [ "${CDHIST[$i]}" = "$PWD" ]
121			then
122				break
123			fi
124			((i=i+1))
125		done
126	
127		if ((i>22))				# limit max size of list
128		then
129			i=22
130		fi
131	
132		while (((i=i-1)>=0))			# bump old dirs in list
133		do
134			CDHIST[i+1]=${CDHIST[i]}
135		done
136	
137		CDHIST[0]=$PWD				# insert new directory in list
138	}
139	
140	
141	function _pwd
142	{
143		if [ -n "$ECD" ]
144		then
145			pwd 1>&6
146		fi
147	}
148	# Start of test
149	cd /tmp
150	cd /bin
151	cd /etc
152	cd -
153	cd -2
154	cd -l
155expected-stdout:
156	/bin
157	/tmp
158	  3 /
159	  2 /etc
160	  1 /bin
161	  0 /tmp
162---
163