lib/directories (cd): Refactor

* lib/directories (cd): Adjust style of `cd` function
* lib/directories (cd): Use regex to match integers
* lib/directories (cd): Use _omb_util_alias to replace cd
* lib/directories (cd): Update the function description
This commit is contained in:
Koichi Murase 2023-04-09 22:02:09 +09:00
parent 618aa82460
commit dd20d586da

View File

@ -1,29 +1,31 @@
#! 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
# A clone of the Zsh `cd' builtin command. This supports the numbered option
# `-1', `-2', etc.
function _omb_directories_cd {
local oldpwd=$OLDPWD
local -i index
if [[ $# -eq 1 && $1 =~ ^-[1-9]+$ ]]; then
index=${1#-}
if ((index >= ${#DIRSTACK[@]})); then
builtin echo "cd: no such entry in dir stack" >&2
return 1
fi
set -- "${DIRSTACK[$index]}"
set -- "${DIRSTACK[index]}"
fi
builtin pushd . >/dev/null &&
OLDPWD="$oldpwd" builtin cd "$@" &&
oldpwd="$OLDPWD" &&
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
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"
OLDPWD=$oldpwd
}
_omb_util_alias cd='_omb_directories_cd'
_omb_util_alias cd..='cd ../' # Go back 1 directory level (for fast typers)
_omb_util_alias ..='cd ../' # Go back 1 directory level
@ -47,7 +49,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
_omb_util_alias po='popd'
# List directory contents
_omb_util_alias lsa='ls -lha'