NBash
78 строк · 2.0 Кб
1#!/usr/bin/env bash
2
3PATH="..:$PATH"
4
5# Load argsparse library.
6. argsparse.sh
7
8# You can also change the way options are set by defining a function
9# named set_option_<optionname>.
10argsparse_use_option option1 "An option." value type:hexa
11
12set_option_option1() {
13local option=$1
14local value=$2
15# You can do own stuff here. Whatever you want, including,
16# transforming the value, calling other functions, performing some
17# actions..
18# E.g: you could enforce the 0x in front of a user-given
19# hexadecimal value.
20if [[ "$value" != 0x* ]]
21then
22value="0x$value"
23fi
24# This is the original argsparse setting action.
25argsparse_set_option_with_value "$option" "$value"
26}
27
28# For options without value.
29argsparse_use_option option2 "Another option."
30
31set_option_option2() {
32local option=$1
33# Again, you can do whatever you want here.
34: some command with some params.
35# You dont have to do it, but it makes sense to call in the end
36# the original argsparse action.
37argsparse_set_option_without_value "$option"
38}
39
40# This is a way to re-implement a cumulative option if you're
41# satisfied with the 'cumulative' property.
42argsparse_use_option cumul "A cumulative option." value
43
44all_cumul_values=()
45set_option_cumul() {
46local option=$1
47local value=$2
48# Append the value to the array.
49all_cumul_values+=( "$value" )
50# Doing this will prevent the argsparse_is_option_set test from
51# returning false.
52argsparse_set_option_with_value "$option" 1
53}
54
55#
56printf -v argsparse_usage_description "%s\n" \
57"A tutorial script teaching how to change the way options are set." \
58"Try command lines such as:" \
59" $0" \
60" $0 -h" \
61" $0 --option1 123a" \
62" $0 --option2" \
63" $0 --cumul first --cumul second --cumul other"
64
65# Command line parsing is done here.
66argsparse_parse_options "$@"
67
68printf "Options reporting:\n"
69# Simple reporting function.
70argsparse_report
71printf "End of argsparse report.\n\n"
72
73printf "These are all the 'cumul' option values:\n"
74i=0
75for v in ${all_cumul_values[@]}
76do
77printf "Value #%d: %s\n" $((++i)) "$v"
78done
79