I am creating a script that will process Cisco serial numbers and produce their manufacturing date.
I am using the following array to handle the Month portion and that works with no issue. That array is setup as so:
declare -A d_year
d_year[10]="2006"
d_year[11]="2007"
d_year[12]="2008"
d_year[13]="2009"
d_year[14]="2010"
d_year[15]="2011"
The issue comes from the Month portion since numbers 1 ~ 5 = January, 6 ~ 9 = February. I have tried the following but to no avail:
declare -A d_month
d_month[{1:5}]="January"
d_month[{6..9}]="February"
d_month[{10..14}]="March"
When it attempts to process the serial number, the year portion comes out with no issues but the month produces the following error(it produces error for the other ill formatted sections of the array):
syntax error: operand expected (error token is "{15..18}")
I can do it line by line but feel that there is an easier way that I may be missing? So my question is, is it possible to create an array in this way to process a range of numbers?
Would you please try:
for m in {1..5}; do d_month[$m]="January"; done
for m in {6..10}; do d_month[$m]="February"; done
for m in {11..15}; do d_month[$m]="March"; done
IMHO case
is the right choice for that, could you try this
#!/bin/bash
d_year=$1
d_month=$2
case $d_year in
10) year="2006";;
11) year="2007";;
12) year="2008";;
13) year="2009";;
14) year="2010";;
15) year="2011";;
esac
case $d_month in
[1-5]) month="January" ;;
[6-9]) month="February";;
1[0-4]) month="March" ;;
esac
echo $month $year
Usage
$ ./test 12 14
March 2008
I created a small script that shows you how to achieve this using a custom function:
#!/bin/bash
declare -A d_month;
function put() {
for i in $(seq $1 $2); do
d_month[$i]="$3";
done;
}
put 1 5 "January";
put 6 9 "February";
put 10 14 "March";
for i in "${!d_month[@]}"; do
echo "$i => ${d_month[$i]}";
done;
The for
loop at the bottom is just to show the contents of the array, and is not part of the functionality of the funtion.
Integer based arrays can be defined in several ways. A less common way is the use of
a=( [20]="value" [30]="value" )
which creates an integer-based array with 2 elements with index 20 and 30.
This can now be exploited using printf
and eval
:
d_year=( [10]=2006 [11]=2007 [12]=2008 [13]=2009 [14]=2010 [15]=2011 )
d_month=()
eval d_month+=( $(printf '[%d]="January" ' {1..5} ) )
eval d_month+=( $(printf '[%d]="February" ' {6..9} ) )
eval d_month+=( $(printf '[%d]="March" ' {10..14}) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.