#!/bin/sh export STACKCD stackcd() { local action="$1" # e.g. 'push' or 'pop' or 'dirs' or ~3 local i case "$action" in '~'[0-9]) i=0 for _ in $STACKCD; do { case "$action" in '~'$i) cd $_ return $? ;; esac i=$((i+1)) } done ;; dirs) i=0 for _ in $STACKCD; do { printf '%i %s\n' "$i" "$_" } done ;; push) STACKCD="$PWD $STACKCD" ;; pop) set -- $STACKCD cd "$1" || return 1 shift STACKCD="$*" ;; esac } stackcd push . cd /tmp stackcd push . stackcd dirs stackcd ~1 stackcd pop