Bash · 1405 bytes Raw Blame History
1 # defines a function named "up" that:
2 # - counts how many arguments ($#) were passed
3 # - does `cd ..` exactly that many times plus one
4 #
5 # In other words:
6 # up → $# = 0 → 1 parent
7 # up up → $# = 1 → 2 parents
8 # up up up → $# = 2 → 3 parents
9 #
10 # This pattern applies to `bk` too
11 # NOTE: no it doesn't
12 #
13
14 up() {
15 # $# is “number of additional words” you typed
16 local n
17 n=$(( $# + 1 )) # if no args, n=1; if “up up”, $#=1→n=2; etc.
18
19 # Ensure all arguments are exactly "up"
20 for arg in "$@"; do
21 if [[ "$arg" != "up" ]]; then
22 echo "Error: 'up' only accepts repeated 'up' arguments." >&2
23 return 1
24 fi
25 done
26
27 # Calculate how many levels to go up
28 local n=$(( $# + 1 ))
29 while (( n > 0 )); do
30 builtin cd .. # use builtin cd to avoid recursing into this function
31 (( n-- ))
32 done
33 }
34
35 # NOTE: does not function as intended
36 #
37 # bk() {
38 # # Ensure all arguments are exactly "bk"
39 # for arg in "$@"; do
40 # if [[ "$arg" != "bk" ]]; then
41 # echo "Error: 'bk' only accepts repeated 'bk' arguments." >&2
42 # return 1
43 # fi
44 # done
45
46 # # Determine number of toggles: if no args, toggle once; else toggle once per "bk"
47 # local count
48 # if (( $# == 0 )); then
49 # count=1
50 # else
51 # count=$#
52 # fi
53
54 # while (( count > 0 )); do
55 # builtin cd -
56 # (( count-- ))
57 # done
58 # }