forked from westonruter/misc-cli-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcdup
executable file
·57 lines (49 loc) · 1.59 KB
/
cdup
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
#!/bin/bash
# Usage: cdup [DIRNAME]
# Author: Weston Ruter (@westonruter) <http://weston.ruter.net/>
# URL: https://github.com/westonruter/misc-cli-tools/blob/master/cdup
# See also: https://github.com/westonruter/misc-cli-tools/blob/master/cddown
#
# Bash shortcut function to cd you to ancestor directory named as first argument.
# If DIRNAME is not supplied, then .. is used.
# Stop having to cd ../../../..
# Also supports substring matches for ancestor directory names.
# Use `cd -` to undo, to restore old working directory.
# Use aliases for common directories, like: alias docroot="cdup docroot".
# Provide a '...' alias to this for great justice.
# Add function to your ~/.profile
# @todo Add bash tab completion
#
# Example:
# $ pwd
# > /var/www/html/example.com/docroot/long/path/to/something
# $ cdup html
# $ pwd
# > /var/www/html
# $ cd -
# $ pwd
# > /var/www/html/example.com/docroot/long/path/to/something
# $ cdup example
# $ pwd
# > /var/www/html/example.com
function cdup {
# TODO: Allow an integer parameter to define the number of levels to jump up; allow it to be used with a named arg
if [ $# == 0 ]; then
cd ..
return 0
fi
dir="$1"
old=`pwd`
# Try matching the full segment in path name
new=`perl -pe "s{(.*/\Q$dir\E)(?=/|$).*?$}{\1};" <<< $old`
# If failed, try partial match of segment
if [ "$old" == "$new" ]; then
new=`perl -pe "s{(.*/[^/]*?\Q$dir\E[^/]*?)(?=/|$).*?$}{\1}" <<< $old`
fi
# No replacements done, so we failed
if [ "$old" == "$new" ]; then
echo "Can't find '$dir' among ancestor directories ($old == $new)." 1>&2
return 1
fi
cd $new
}