यदि आप दोनों का उपयोग करना चाहते हैं -r ..., .. और -r ... -r ... -r ...: इस तरह के रूप में एक स्क्रिप्ट बनाएँ "toto.bash":
#!/usr/bin/bash
add_ranges () #this will add each integers or ranges (a-b) into the array: myarray
{
#first we test that we only have those validchars (makes the second step below much easier to write)
validchars='[1234567890,-]'
echo "$@" | grep "${validchars}" >/dev/null && {
: ; #only valid chars, probably ok. (but could be wrong, ex: 1- 2,, 4-3 etc...)
} || {
echo "The ranges you entered are not valid : they should only contain such characters: ${validchars}"
exit 1 ;
}
#secondly we now try to handle the current ranges lists (comma separated)
for range in $(echo "${@}" | tr ',' ' ')
do
if [[ ${range} =~ ^[0-9]+$ ]] # [[ can handle regexp matching, and doesn't need to quote parameters
then
myarray[${#myarray[*]}]=${range} #add this after the latest element in myarray
elif [[ ${range} =~ ^[0-9]+-[0-9]+$ ]]
then
newrange=$(echo "$range" | sed -e 's/-/../')
for i in `eval echo {$newrange}` # {a..b} means: all integers a to b
do
myarray[${#myarray[*]}]=${i} #add this after the latest element in myarray
done
else
echo "ERROR: I can not recognize this range: $range"
exit 1
fi
done
}
###### handle options using getopts:
OPTIND=1; #here for compatibility's sake: in case you add another function that uses getopts, reminds you to re-set OPTIND each time.
while getopts "r:" zeoption; do
case $zeoption in
r)
allranges="${OPTARG}";
add_ranges "${OPTARG}";
;;
-)
echo "option --, OPTARG=$OPTARG";
break ;
;;
*)
echo "ERROR: Unrecognized option: zeoption=$zeoption OPTARG=$OPTARG";
shift
;;
esac;
done;
shift $((OPTIND-1)) ; #we shift away all the options we processed.
###### end of options handling
# and we continue here...
echo "we now have : remaining arguments: ${@}"
echo "and myarray contains: ${myarray[@]}"
और फिर इसे चलाएं:
$ ./toto.bash -r 2,4,6-12 -r 100-103 foo bar
we now have : remaining arguments: foo bar
and myarray contains: 2 4 6 7 8 9 10 11 12 100 101 102 103
मैं सिर्फ संकेत देना चाहता था, लेकिन यह कहना कि इसे लिखना बेहतर है। यह लंबे उत्तर के लिए बनाता है, लेकिन मुझे आशा है कि यह मदद करता है!
{2..4}
?