The reason why this doesn't work automaticall ATOW is a known bash bug which prevents exporting array variables (see section bugs in man page). Unfortunately DIRSTACK is an array variable.
I created replacements for pushd/popd/dirs which wrap them but store their stuff in a scalar variable, so that children processes are aware of it.
If you source the code below and use mypushd/mypopd/mydirs instead of the originals, children processes will remember their parents' stack. Notice that this won't work with directories whose name includes a colon!
Please warn me if you spot any bug, 'cause I just wrote that. Also, if you know of a simpler alternative, please share!
export SCALARDIRSTACK
export DIRSTACK
update_dirstack()
{
if [ ! -z "$SCALARDIRSTACK" ]; then
dirs -c
# get an array from scalardirstack
IFS=':' read -a tmp <<< "$SCALARDIRSTACK"
# traverse in reverse order to pushd stuff into the stack
for (( idx=${#tmp[@]}-1 ; idx>=0 ; idx-- )) ; do
# gotta use pushd/popd this to manipulate DIRSTACK
pushd -n ${tmp[idx]} > /dev/null
done
fi
}
update_scalardirstack()
{
if [ ${#DIRSTACK[@]} -gt 1 ]; then
SCALARDIRSTACK=$(printf '%q:' ${DIRSTACK[@]:1}) # string from array
else
SCALARDIRSTACK=""
fi
}
scalar_dstack_wrap()
{
update_dirstack
$@
update_scalardirstack
}
alias mydirs='scalar_dstack_wrap dirs'
alias mypushd='scalar_dstack_wrap pushd'
alias mypopd='scalar_dstack_wrap popd'
export -p
). So this should work automatically! Well, it doesn't because of a known bash bug that prevents arrays from being exported (see section BUGS in the man pages) :S