-
Notifications
You must be signed in to change notification settings - Fork 10
/
up.sh
executable file
·89 lines (68 loc) · 1.27 KB
/
up.sh
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
89
#!/usr/bin/env sh
# up.sh: Quickly traverse up the current working path.
# Author: Shannon Moeller <[email protected]>
# Source to use: [ -f /path/to/up.sh ] && . /path/to/up.sh
__updir() {
if [[ "$1" == "/" || -z "$1" || -z "$2" ]]; then
return
fi
local p="$(dirname "$1")"
local a="$(basename "$p")"
local b="$(basename "$2")"
if [[ -z "$a" || -z "$b" ]]; then
return
fi
if [[ "$a" == "$b"* ]]; then
echo "$p"
return
fi
__updir "$p" "$2"
}
__upnum() {
if [[ -z "$1" || -z "$2" || ! "$2" =~ ^[0-9]+$ ]]; then
return
fi
local p="$1"
local i="$2"
while (( i-- )); do
p="$(dirname "$p")"
done
echo "$p"
}
_up() {
local p="$(dirname $PWD)"
local w="${COMP_WORDS[COMP_CWORD]}"
COMPREPLY=( $(IFS=';' compgen -S/ -W "${p//\//;}" -- "$w") )
}
up() {
# up one
if (( ! $# )); then
cd ..
return
fi
# up dir
local d="$(__updir "$PWD" "$1")"
if [[ -d "$d" ]]; then
cd "$d"
return
fi
# up num
local n="$(__upnum "$PWD" "$1")"
if [[ -d "$n" ]]; then
cd "$n"
return
fi
# fallback
if [[ $1 == - || -d $1 ]]; then
cd $1
return
fi
# usage
echo -e "usage: up [dir|num|-]\npwd: $PWD"
}
# zsh compatibility
if [[ -n ${ZSH_VERSION-} ]]; then
autoload -U +X bashcompinit && bashcompinit
fi
# tab-completion
complete -o nospace -F _up up