ksh implementation of pushd, popd, and dirs.

gilbert harrus gh at bdblues.altair.fr
Wed Jan 30 00:23:50 AEST 1991


Newsgroups: comp.unix.shell
Subject: ksh emulation of dirs, pushd, and popd of csh
Summary: 
Expires: 
Sender: 
Followup-To: 
Distribution: world
Organization: Gip Altair/INRIA, France
Keywords: 

Somebody asked for examples of ksh scripts. I just moved from [t]csh
to ksh, and I wrote this "package" to learn more about ksh.

Save in a file, say dirs.ksh, and type : eval . dirs.ksh
Not extensively tested...

gilbert harrus

<--------------- cut here------------------------------>
# Emulation of dirs, pushd and popd of csh under ksh
# Send comments (and bug fixes!) to gh at bdblues.altair.fr

dirs() {
	stackdir[0]=`pwd`
	typeset -i i=0
	while let i!=ndirs ; do
# use print rather than echo here as -n is bsdish
		print -n "${stackdir[$i]} "
		let i=i+1
	done
	print
	return 0
}

pushd() {
	stackdir[0]=`pwd`
	typeset -i i j k 

	if [ $# -gt 1 ]; then
		echo "pushd: Too many arguments."
		return 1
	fi

	case "$1" in
# 3 digits less than 200 (otherwise interpreted as a directory name)
	+[1-9]|+[1-9][0-9]|+0[1-9]|+0[1-9][0-9]|+1[0-9][0-9])
		let i=$1
		if [ $i -ge $ndirs ] ; then
			echo "pushd: Directory stack not that deep."
			return 1
		fi
# copy  from 0..i-1 to ndirs..ndirs+i-1
		let j=0
		let k=ndirs
		while let j!=i ; do
			stackdir[$k]=${stackdir[$j]}
			let j=j+1
			let k=k+1
			if [ $k -ge 511 ] ; then
				echo "pushd: fatal internal error."
				return 1
			fi
		done
# move from i to ndirs+i-1 to 0..ndirs-1
		let j=i
		let k=0
		while let k!=ndirs ; do
			stackdir[$k]=${stackdir[$j]}
			let j=j+1
			let k=k+1
		done
		cd ${stackdir[0]}
		;;

	*)	cd $1
		if [ $? -ne 0 ]; then
			return 1
		fi
		let i=ndirs
		let ndirs=ndirs+1
		let j=i-1
		while let i!=0 ; do
			stackdir[$i]="${stackdir[$j]}"
			let i=i-1
			let j=j-1
		done
		;;
	esac
	dirs
	return $?
}

popd() {
	typeset -i i

	if [ $# -gt 1 ]; then
		echo "popd: Too many arguments."
		return 1
	fi

# if there is one argument check that it is a +n, with n<ndirs
# set j to position of the entry to be disgarded.
	if [ $# -eq 1 ]; then
	case "$1" in
	+[1-9]|+[1-9][0-9]|+0[1-9]|+0[1-9][0-9]|+1[0-9][0-9])
		let j=$1
		if [ $j -ge $ndirs ]; then
			echo "popd: Directory stack not that deep."
			return 1
		fi
		;;
	*)
		echo "pushd: Bad directory."
		return 1
		;;
	esac
	else
		let j=0
	fi

	let i=ndirs
	if [ $i -eq 1 ] ; then
		echo "popd: Directory stack empty."
		return 1
	fi
	let ndirs=ndirs-1
	let k=j+1
	while let j!=i ; do
		stackdir[$j]="${stackdir[$k]}"
		let j=j+1
		let k=k+1
	done
	cd ${stackdir[0]}
	dirs
	return $?
}
	
stackdir=`pwd`
typeset -i ndirs=1
typeset -f dirs
typeset -f pushd
typeset -f popd



More information about the Comp.unix.shell mailing list