From 618aa82460383d9f1d646c6de30d287c8f5ec0c3 Mon Sep 17 00:00:00 2001 From: Chai Feng Date: Mon, 26 Aug 2019 23:38:02 +0800 Subject: [PATCH] lib/directories: Add `cd` function, a clone of Zsh cd builtin command * Fix, the `~` in the first item of `DIRSTACK` may not be expanded in Cygwin Bash --- lib/directories.sh | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/lib/directories.sh b/lib/directories.sh index 7be0702..8b16093 100644 --- a/lib/directories.sh +++ b/lib/directories.sh @@ -1,5 +1,30 @@ #! bash oh-my-bash.module # Common directories functions + +# A clone of Zsh `cd` builtin command +function cd() { + declare oldpwd="$OLDPWD" + declare -i index + if [[ "$#" -eq 1 && "$1" == -[1-9]* ]]; then + index="${1#-}" + if [[ "$index" -ge "${#DIRSTACK[@]}" ]]; then + builtin echo "cd: no such entry in dir stack" >&2 + return 1 + fi + set -- "${DIRSTACK[$index]}" + fi + builtin pushd . >/dev/null && + OLDPWD="$oldpwd" builtin cd "$@" && + oldpwd="$OLDPWD" && + builtin pushd . >/dev/null && + for ((index="${#DIRSTACK[@]}"-1; index>=1; index--)); do + if [[ "${DIRSTACK[0]/#~/$HOME}" == "${DIRSTACK[$index]}" ]]; then + builtin popd "+$index" >/dev/null || return 1 + fi + done + OLDPWD="$oldpwd" +} + _omb_util_alias cd..='cd ../' # Go back 1 directory level (for fast typers) _omb_util_alias ..='cd ../' # Go back 1 directory level _omb_util_alias ...='cd ../../' # Go back 2 directory levels @@ -22,6 +47,7 @@ _omb_util_alias 9='cd -9' _omb_util_alias md='mkdir -p' _omb_util_alias rd='rmdir' _omb_util_alias d='dirs -v | head -10' +_omb_util_alias po=popd # List directory contents _omb_util_alias lsa='ls -lha'