NBash
77 строк · 2.1 Кб
1#!/usr/bin/env bash
2
3PATH="..:$PATH"
4
5# Load argsparse library.
6. argsparse.sh
7
8# Declaring an option not accepting a value and not having a
9# single-char equivalent.
10argsparse_use_option option1 "An option."
11
12# Declaring an option not accepting a value but with a single-char
13# equivalent.
14
15# "short" is a property, and "o" is the value of the "short" property
16# for this option. Argsparse can handle other properties, see other
17# tutorials.
18argsparse_use_option option2 "Another option." short:o
19
20# Alternative syntax to declare an option with a single-char
21# equivalent. A '=' char can be put prior to a char in the option name
22# to make a single-letter equivalent. e.g:
23argsparse_use_option o=ption3 "A 3rd option."
24# does the same as:
25# argsparse_use_option option3 "A 3rd option." short:p
26
27# You can declare an option without property...
28argsparse_use_option option4 "A 4th option."
29# ... and set a property after the declaration using the
30# argsparse_set_option_property function.
31argsparse_set_option_property short:4 option4
32
33# argsparse_usage_description is a simple variable printed at the end
34# of the usage function invocation.
35printf -v argsparse_usage_description "%s\n" \
36"A tutorial script for argsparse basics." \
37"Try command lines such as:" \
38" $0" \
39" $0 -h" \
40" $0 --option1" \
41" $0 --option1 -h" \
42" $0 --option2" \
43" $0 -o -p -4" \
44" $0 -op4" \
45" $0 --doesnt-exist" \
46" $0 --option1 -o -o -o one two 5"
47
48# Command line parsing is done here.
49argsparse_parse_options "$@"
50
51printf "Options reporting:\n"
52# Simple reporting function.
53argsparse_report
54printf "End of argsparse report.\n\n"
55
56for option in option{1..4}
57do
58# This is the way you should test your options....
59if argsparse_is_option_set "$option"
60then
61printf "%s was set %d time(s) on the command line.\n" \
62"$option" \
63"${program_options[$option]}" # ... and this is the way
64# you should access them.
65else
66printf "%s was not on the command line.\n" "$option"
67fi
68done
69printf "\n"
70
71i=1
72# You can access all other script parameters through the
73# program_params array.
74for param in "${program_params[@]}"
75do
76printf "Parameter #%d: %s\n" $((i++)) "$param"
77done
78