-
Notifications
You must be signed in to change notification settings - Fork 112
/
bd.zsh
88 lines (67 loc) · 2.04 KB
/
bd.zsh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# shellcheck shell=bash
bd () {
(($#<1)) && {
printf -- 'usage: %s <name-of-any-parent-directory>\n' "${0}"
printf -- ' %s <number-of-folders>\n' "${0}"
return 1
} >&2
local requestedDestination="${1}"
local -a parents=(${(ps:/:)"${PWD}"})
local numParents
local dest
local i
local parent
# prepend root to the parents array
parents=('/' "${parents[@]}")
# Remove the current directory since it isn't a parent
shift -p parents
# Get the number of parent directories
numParents="$(( ${#parents[@]}))"
# Build dest and 'cd' to it by looping over the parents array in reverse
dest='./'
for i in $(seq "${numParents}" -1 1); do
parent="${parents[${i}]}"
dest+='../'
if [[ "${requestedDestination}" == "${parent}" ]]; then
cd $dest
return $?
fi
done
# If the user provided an integer, go up as many times as asked
dest='./'
if [[ "${requestedDestination}" == <-> ]]; then
if [[ "${requestedDestination}" -gt "${numParents}" ]]; then
printf -- '%s: Error: Can not go up %s times (not enough parent directories)\n' "${0}" "${requestedDestination}"
return 1
fi
for i in {1.."${requestedDestination}"}; do
dest+='../'
done
cd "${dest}"
return $?
fi
# If the above methods fail
printf -- '%s: Error: No parent directory named "%s"\n' "${0}" "${requestedDestination}"
return 1
}
_bd () {
# Get parents (in reverse order)
local localMatcherList
local -a parents=(${(ps:/:)"${PWD}"})
local numParents
local i
local -a parentsReverse
zstyle -s ':completion:*' 'matcher-list' 'localMatcherList'
# prepend root to the parents array
parents=('/' "${parents[@]}")
# Remove the current directory since it isn't a parent
shift -p parents
# Get the number of parent directories
numParents="$(( ${#parents[@]}))"
parentsReverse=()
for i in $(seq "${numParents}" -1 1); do
parentsReverse+=("${parents[${i}]}")
done
compadd -V 'Parent directories' -M "${localMatcherList}" "$@" -- "${parentsReverse[@]}"
}
compdef _bd bd