aboutsummaryrefslogtreecommitdiff
path: root/bin/apf
blob: 17a30be94ea949aaa9429f1277b26e5e44327a68 (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
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
#!/bin/sh
# Prepend arguments from a file to the given arguments for a command
self=apf

# Require at least two arguments
if [ "$#" -lt 2 ] ; then
    printf >&2 '%s: Need an arguments file and a command\n' "$self"
    exit 2
fi

# First argument is the file containing the null-delimited arguments
argf=$1 cmd=$2
shift 2

# If the file exists, we'll read it. If it doesn't, this is not an error (think
# personal config files like ~/.vimrc)
if [ -f "$argf" ] ; then

    # Create a temporary directory with name in $td, and handle POSIX-ish traps to
    # remove it when the script exits.
    td=
    cleanup() {
        [ -n "$td" ] && rm -fr -- "$td"
        if [ "$1" != EXIT ] ; then
            trap - "$1"
            kill "-$1" "$$"
        fi
    }
    for sig in EXIT HUP INT TERM ; do
        # shellcheck disable=SC2064
        trap "cleanup $sig" "$sig"
    done
    td=$(mktd "$self") || exit

    # Write the arguments in reverse to a temporary file
    revf=$td/revf
    sed '1!G;$!{h;d}' "$argf" > "$revf" || exit

    # Stack up all the arguments from the file. Skip blank lines and comments.
    # An empty file is also fine.
    while IFS= read -r arg ; do
        case $arg in
            '#'*) continue ;;
            *[![:space:]]*) ;;
            *) continue ;;
        esac
        set -- "$arg" "$@"
    done < "$revf"

    # We can remove the temporary stuff now, which allows us to exec safely
    cleanup ''
fi

# Run the command with the changed arguments
exec "$cmd" "$@"