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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#!/usr/bin/env bash
PATH="..:$PATH"
# Load argsparse library.
. /usr/share/bash-argsparse/argsparse.sh
# Declaring an option not accepting a value and not having a
# single-char equivalent.
argsparse_use_option option1 "An option."
# Declaring an option not accepting a value but with a single-char
# equivalent.
# "short" is a property, and "o" is the value of the "short" property
# for this option. Argsparse can handle other properties, see other
# tutorials.
argsparse_use_option option2 "Another option." short:o
# Alternative syntax to declare an option with a single-char
# equivalent. A '=' char can be put prior to a char in the option name
# to make a single-letter equivalent. e.g:
argsparse_use_option o=ption3 "A 3rd option."
# does the same as:
# argsparse_use_option option3 "A 3rd option." short:p
# You can declare an option without property...
argsparse_use_option option4 "A 4th option."
# ... and set a property after the declaration using the
# argsparse_set_option_property function.
argsparse_set_option_property short:4 option4
# argsparse_usage_description is a simple variable printed at the end
# of the usage function invocation.
printf -v argsparse_usage_description "%s\n" \
"A tutorial script for argsparse basics." \
"Try command lines such as:" \
" $0" \
" $0 -h" \
" $0 --option1" \
" $0 --option1 -h" \
" $0 --option2" \
" $0 -o -p -4" \
" $0 -op4" \
" $0 --doesnt-exist" \
" $0 --option1 -o -o -o one two 5"
# Command line parsing is done here.
argsparse_parse_options "$@"
printf "Options reporting:\n"
# Simple reporting function.
argsparse_report
printf "End of argsparse report.\n\n"
for option in option{1..4}
do
# This is the way you should test your options....
if argsparse_is_option_set "$option"
then
printf "%s was set %d time(s) on the command line.\n" \
"$option" \
"${program_options[$option]}" # ... and this is the way
# you should access them.
else
printf "%s was not on the command line.\n" "$option"
fi
done
printf "\n"
i=1
# You can access all other script parameters through the
# program_params array.
for param in "${program_params[@]}"
do
printf "Parameter #%d: %s\n" $((i++)) "$param"
done
|