Wednesday, 8 June 2016

Integer Arrays in Bash

For reference I am on Ubuntu 15.10. This is something again I really struggled with hence thought it best to document

If you are one of those trying to use an Integer Array in a bash script, for example if your trying to identify how many days in a month for a particular year you might want to store in 2 integer arrays, one for a leap year and the other for a normal year. In my case I was trying to find the day of the year from the date provided.

Again what I found out there was a comma separated values, hence my array looked like this

  DAYS_IN_MONTHS=( 31,28,31,30,31,30,31,31,30,31,30,31 )
  DAYS_IN_MONTHS_LEAP_YEAR=( 31,29,31,30,31,30,31,31,30,31,30,31 )

But when I kept looping through the array as below, it still didn't work

  for((i=0;i<limit;i++))
    do
      if [ $[$year % 400] -eq 0 ]; then
        current=${DAYS_IN_MONTHS_LEAP_YEAR[$i]}
      elif [ $[$year % 4] -eq 0 ]; then
        if [ $[$year % 100] -ne 0 ]; then
          current=${DAYS_IN_MONTHS_LEAP_YEAR[$i]}
        else
          current=${DAYS_IN_MONTHS[$i]}
        fi
      else
        current=${DAYS_IN_MONTHS[$i]}
      fi
   dayOfYear=$((dayOfYear+current))
  done

When I did an echo on DAYS_IN_MONTHS[$i] within the loop it seemed to be displaying the entire array as the first element.

Totally confused as to why it wasn't working, am sure all of you know about how important spaces are in bash, I finally figured it was a space issue.

When I changed the arrays into the below, I was now getting individual elements but except the last element, everything had a comma(',') suffixed. 

  DAYS_IN_MONTHS=( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 )
  DAYS_IN_MONTHS_LEAP_YEAR=( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 )

So the next logical step was to remove the ',' from each element as below and that made it work.

  DAYS_IN_MONTHS=( 31 28 31 30 31 30 31 31 30 31 30 31)
  DAYS_IN_MONTHS_LEAP_YEAR=( 31 29 31 30 31 30 31 31 30 31 30 31)

Hope that helps someone?

No comments:

Post a Comment