summaryrefslogtreecommitdiffhomepage
path: root/tests/scripts/cli-tool.sh
blob: 7b88d06badb6cbf1fced72816dff59668d6bab0e (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
# Integration: a command-line tool with options, usage and exit codes,
# run as a separate script the way a user would.
cat >tool <<'TOOL'
usage() { echo "usage: tool [-v] [-n count] [-o file] word..." >&2; exit 2; }
verbose=0 count=1 out=
while getopts vn:o: opt; do
    case $opt in
    v) verbose=$((verbose + 1)) ;;
    n) case $OPTARG in ''|*[!0-9]*) echo "tool: bad count: $OPTARG" >&2; exit 2 ;; esac
       count=$OPTARG ;;
    o) out=$OPTARG ;;
    *) usage ;;
    esac
done
shift $((OPTIND - 1))
[ $# -gt 0 ] || usage
[ $verbose -gt 0 ] && echo "verbose=$verbose count=$count words=$#" >&2
run() {
    i=0
    while [ $i -lt "$count" ]; do
        printf '%s\n' "$*"
        i=$((i + 1))
    done
}
if [ -n "$out" ]; then run "$@" >"$out"; else run "$@"; fi
TOOL
t() { $TSH tool "$@"; echo "[exit $?]"; }
t hello
t -n 3 a b
t -vv -n2 x 2>&1
t -o result -n 2 saved; cat result
t
t -n abc x
t -q x 2>/dev/null
t -- -n