Skip to content

Instantly share code, notes, and snippets.

@saagarjha
Last active February 24, 2018 23:32
Show Gist options
  • Save saagarjha/f9e9186479975d36dc18b15a87849205 to your computer and use it in GitHub Desktop.
Save saagarjha/f9e9186479975d36dc18b15a87849205 to your computer and use it in GitHub Desktop.
Bash function that provides a similar experience to zsh's cd history
cd() {
# Set the current directory to the 0th history item
cd_history[0]=$PWD
if [[ $1 == -h ]]; then
for i in ${!cd_history[@]}; do
echo $i: "${cd_history[$i]}"
done
return
elif [[ $1 =~ ^-[0-9]+ ]]; then
builtin cd "${cd_history[${1//-}]}" || # Remove the argument's dash
return
else
builtin cd "$@" || return # Bail if cd fails
fi
# cd_history = ["", $OLDPWD, cd_history[1:]]
cd_history=("" "$OLDPWD" "${cd_history[@]:1:${#cd_history[@]}}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment