aboutsummaryrefslogtreecommitdiff
path: root/sh/shrc.d/gt.sh
blob: d18a4ab84eae6543713202ccc5eb34281465fbd1 (plain) (blame)
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
# If the argument is a directory, change to it. If it's a file, change to its
# parent. Stands for "get to".
gt() {

    # Check argument count
    if [ "$#" -gt 1 ] ; then
        printf >&2 'gd(): Too many arguments\n'
        return 2
    fi

    # Strip trailing slash
    set -- "${1%/}"

    # If target doesn't have a leading slash, add PWD prefix
    case $1 in
        /*) ;;
        *) set -- "${PWD%/}"/"$1"
    esac

    # If target isn't a directory, chop to its parent
    [ -d "$1" ] || set -- "${1%/*}"

    # If target is now empty, go to the root
    [ -n "$1" ] || set -- /

    # Try to change into the determined directory
    command cd -- "$@"
}