summaryrefslogtreecommitdiff
path: root/nextbin
blob: 3a7a4e64920d87ad9df334e1bb58af52f805e21d (plain)
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
#!/bin/sh

set -e

die() {
    fmt=$1
    shift
    printf "nextbin %s failed: $fmt\n" "$orig_exe" "$@" >&2
    exit 1
}

usage() {
    # shellcheck disable=SC2016
    echo 'usage: nextbin [-v] "$0" "$@"' >&2
}

case "$1" in
    -v) action="echo"; shift;;
    -*|'') usage; exit 1;;
    *) action="exec"
esac
orig_exe=$1
shift
exe_name=${orig_exe##*/}

[ -n "$PATH" ] || die 'PATH is empty'

path=$PATH
phase=1
found=
while :; do
    exe=${path%%:*}/$exe_name
    if [ -f "$exe" ] && [ -x "$exe" ]; then
        if [ "$phase" = 1 ]; then
            if [ "$exe" -ef "$orig_exe" ]; then
                phase=2
            fi
        elif [ "$exe" -ef "$orig_exe" ]; then
            if [ -n "$found" ]; then
                die 'duplicate PATH entries found'
            fi
        elif [ -z "$found" ]; then
            found=$exe
        fi
    fi
    case $path in
        *:*) path=${path#*:} ;;
        *) break ;;
    esac
done

[ "$phase" != 1 ] || found=$(command -v "$exe_name") || die '%s is not in PATH' "$orig_exe"
[ -n "$found" ] || die '%s is last instance' "$orig_exe"
$action "$found" "$@"