-
Notifications
You must be signed in to change notification settings - Fork 0
/
dir_stack.shlib
55 lines (54 loc) · 3.25 KB
/
dir_stack.shlib
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
type pushd >/dev/null 2>&1 || pushd() {
# === Initialize ===================================================
case "${DIR_STACK:-}" in '') DIR_STACK=$(pwd);; esac
# === Try to change directory ======================================
cd "$1" >/dev/null 2>&1 || {
echo "${0##*/}: pushd: $1: No such file or directory" 1>&2
return 1
}
# === Push the directory stack =====================================
DIR_STACK=$(printf '%s\n%s' "$(pwd)" "$DIR_STACK")
# === Print the contents in the stack ==============================
printf '%s' "$DIR_STACK" |
awk '# --- Replace the prefix of the homedirectory path with "~" if possible #
BEGIN {homedir=ENVIRON["HOME"]; #
hd_len =length(homedir); #
while (getline dir) { #
if ( homedir == "" ) {print dir; continue;} #
if ((homedir == "/") && (dir != "/")) {print dir; continue;} #
pos =index(dir,homedir); #
if ( pos != 1 ) {print dir; continue;} #
print "~" substr(dir,pos+hd_len); #
} }' |
tr '\n' ' ' |
grep '' |
sed 's/ $//'
}
type popd >/dev/null 2>&1 || popd() {
# === Initialize ===================================================
set -- "$(printf '%s\n' "${DIR_STACK:-}" | tail -n +2)"
set -- "$1" "$(printf '%s\n' "$1" | head -n 1)"
case "$2" in '') echo "${0##*/}: popd: directory stack empty" 1>&2; return 1;; esac
# === Try to change directory to the top of the stack ==============
cd "$2" >/dev/null 2>&1 || {
echo "${0##*/}: popd: $1: No such file or directory" 1>&2
return 1
}
# === Pop the directory stack ======================================
DIR_STACK=$1
# === Print the contents in the stack ==============================
printf '%s\n' "$1" |
awk '# --- Replace the prefix of the homedirectory path with "~" if possible #
BEGIN {homedir=ENVIRON["HOME"]; #
hd_len =length(homedir); #
while (getline dir) { #
if ( homedir == "" ) {print dir; continue;} #
if ((homedir == "/") && (dir != "/")) {print dir; continue;} #
pos =index(dir,homedir); #
if ( pos != 1 ) {print dir; continue;} #
print "~" substr(dir,pos+hd_len); #
} }' |
tr '\n' ' ' |
grep '' |
sed 's/ $//'
}