Bash cd function
09 Nov 2019I have a cd function I wrote for bash that I kind of like. It has two pieces of functionality that are probably quite useful:
-
If you cd to file via
cd <filename>
it takes you to the parent directory.
-
The cd command stores the last directory you were working in in a file
$HOME/lastdir
. In combination withurxvt -cd `cat $HOME/lastdir`,
I can quickly fire up a new terminal to the last directory I was working in. I think there are other ways to do it, but I like my way since I am able to add exceptions to the lastdir functionality. For example, if I am in a remote filesystem or nfs directory, then due to various problems (e.g., poor network) the
urxvt -cd
command will hang and take forever.
function cd
{
### Configuration ###
# assigning "$@" to a variable helps somehow.
args="$@"
host=$(hostname -a)
# logfile for cd command. Set to empty to not log.
logcd="$HOME/logs/cd-${host}"
# if the current directory matches a list of exceptions, then do not write it to .last_dir
except_dirs='/mnt/sshfs /mnt/box-remote /mnt/nfsmount /media /run/media /home/arjun/201-sshfs'
### End Configuration ###
# the builtin cd is to avoid recursion
if [[ -f "$args" ]]; then
# if asked to cd to a file, find dirname and cd to it
if ! builtin cd "$(dirname "$args")"; then
return 1
fi
else
# directly try the builtin cd on
if ! builtin cd "$args"; then
return 1
fi
fi
cdir=$(pwd) #current directory that the builtin would have changed to if successful
if [[ -w "$logcd" ]]; then
# if logfile for cd is writeable
echo "$cdir" >> "$logcd"
fi
for x in $except_dirs; do
if echo "$cdir" | grep "$x" > /dev/null; then
return 1
# cat $HOME/.last_dir
fi
done
# if any of the except dirs had matched, it would have exited
echo "$cdir" > $HOME/.last_dir
return 0
}