|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +PATH="..:$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>. |
| 10 | +argsparse_use_option option1 "An option." value type:hexa |
| 11 | + |
| 12 | +set_option_option1() { |
| 13 | + local option=$1 |
| 14 | + local 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. |
| 20 | + if [[ "$value" != 0x* ]] |
| 21 | + then |
| 22 | + value="0x$value" |
| 23 | + fi |
| 24 | + # This is the original argsparse setting action. |
| 25 | + argsparse_set_option_with_value "$option" "$value" |
| 26 | +} |
| 27 | + |
| 28 | +# For options without value. |
| 29 | +argsparse_use_option option2 "Another option." |
| 30 | + |
| 31 | +set_option_option2() { |
| 32 | + local 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. |
| 37 | + argsparse_set_otion_without_value "$option" |
| 38 | +} |
| 39 | + |
| 40 | +# This is a way to implement a cumulative option. |
| 41 | +argsparse_use_option cumul "A cumulative option." value |
| 42 | + |
| 43 | +all_cumul_values=() |
| 44 | +set_option_cumul() { |
| 45 | + local option=$1 |
| 46 | + local value=$2 |
| 47 | + # Append the value to the array. |
| 48 | + all_cumul_values+=( "$value" ) |
| 49 | + # Doing this will prevent the argsparse_is_option_set test from |
| 50 | + # returning false. |
| 51 | + argsparse_set_option_with_value "$option" 1 |
| 52 | +} |
| 53 | + |
| 54 | +# |
| 55 | +printf -v argsparse_usage_description "%s\n" \ |
| 56 | + "A tutorial script teaching how to change the way options are set." \ |
| 57 | + "Try command lines such as:" \ |
| 58 | + " $0" \ |
| 59 | + " $0 -h" \ |
| 60 | + " $0 --option1 123a" \ |
| 61 | + " $0 --option2" \ |
| 62 | + " $0 --cumul first --cumul second --cumul other" |
| 63 | + |
| 64 | +# Command line parsing is done here. |
| 65 | +argsparse_parse_options "$@" |
| 66 | + |
| 67 | +printf "Options reporting:\n" |
| 68 | +# Simple reporting function. |
| 69 | +argsparse_report |
| 70 | +printf "End of argsparse report.\n\n" |
| 71 | + |
| 72 | +printf "These are all the 'cumul' option values:\n" |
| 73 | +i=0 |
| 74 | +for v in ${all_cumul_values[@]} |
| 75 | +do |
| 76 | + printf "Value #%d: %s\n" $((++i)) "$v" |
| 77 | +done |
0 commit comments