Nov 30, 2004 19:56
Of course you already know the brilliant BASH feature - save the
command history over different sessions. Note that if you don't
(or if you don't know what the hell is BASH), probably you are
browsing the wrong page :-)
The next small code fragment, if placed in you .bashrc file
allows you to save DIRSTACK over different sessions as well as
command line history. The feature are controled by the following
three environment variables:
------- First code fragment (.bash_profile is a best place for it)
## Saved visited directories list (my addon)
export DIRHISTMAXSIZE=256 # Maximal directory history file size
export DIRHISTSIZE=16 # Save this amount of last visited dirs
export DIRHISTFILE=.bash_dirhistory # Save directory history to this file
------- End of first code fragment
------- Second code fragment (insert it in .bashrc)
###
### Save DIRSTACK on exit
###
trap save_dir_stack EXIT
save_dir_stack()
{
local ndirs=${#DIRSTACK[@]}
local tmp="/tmp/bash-hist-$$"
# ndirs now is an amount of last visited directories to save
if (( $ndirs > $DIRHISTSIZE ))
then
ndirs=$DIRHISTSIZE
fi
# Copy each line to TMP, except already exisitng in DIRSTACK
rm -f $tmp
cat ${HOME}/$DIRHISTFILE | while read line
do
local found=0
for (( i=0; i<$ndirs; i++ ))
do
if [[ "${DIRSTACK[$i]}" == "$line" ]]; then
found=1
break
fi
done
if (( ! $found )); then
echo "$line" >> $tmp
fi
done
# Append currently saved history
for (( i=0; i<$ndirs; i++ ))
do
echo ${DIRSTACK[$i]} >> $tmp
done
# And save it to original file
tail -$DIRHISTMAXSIZE $tmp > ${HOME}/$DIRHISTFILE
rm -f $tmp
}
###
### Restore DIRSTACK
###
restore_dir_stack()
{
local i
local dir
local found
local dirs
local -a hist_dirs
if [[ ! -e ${HOME}/$DIRHISTFILE ]]; then
return
fi
dirs=`dirs` # Existing directories in stack
set -- `cat ${HOME}/$DIRHISTFILE | while read line; \
do \
echo "$line"; \
done`
for dir; do
hist_dirs[${#hist_dirs[*]}]=$dir
done
for (( i=$#-1; i>=0; i-- ))
do
dir=${hist_dirs[$i]}
found=0
for old in $dirs
do
if [[ "$dir" == "$old" ]]; then
found=1
break
fi
done
if (( ! $found )); then
#pushd -n $dir 2>/dev/null 1>&2
pushd -n `echo $dir | sed -e "s#~#${HOME}#"` 2>/dev/null 1>&2
fi
done
}
restore_dir_stack
------ End of second code fragment