0

The for loop does not work if I use the $DAYSDIFF variable but it does work if I type in the number of days since 2020-01-21. When I use $DAYSDIFF, I get an error date: invalid date ‘2020-01-21 + {0..97} day’ Is there a way to use the calculated number of days variable in the "IN" clause of the loop? I'm using Ubuntu 18.04.

REPDATE=2020-01-21 #Date of first COVID-19 report.
CURDATE=`date "+%Y%m%d"` #Todays date.
DAYSDIFF=$(( (`date -d $CURDATE +%s` - `date -d $REPDATE +%s`) / (24*3600) ))
#echo $DAYSDIFF #The correct number of days is echoed.
REPORTNUM=1

for i in {0..$DAYSDIFF} #DAYSDIFF is not working. If I type a number here it works.
do
   NEXT_DATE=$(date +%Y%m%d -d "$REPDATE + $i day")
   echo wget https://www.who.int/docs/default-source/coronaviruse/situation-reports/"$NEXT_DATE"-sitrep-"$REPORTNUM"-covid-19.pdf
   #wget https://www.who.int/docs/default-source/coronaviruse/situation-reports/"$NEXT_DATE"-sitrep-"$REPORTNUM"-covid-19.pdf
   REPORTNUM=`expr $REPORTNUM + 1`
done

  • This is [BashPitfalls #33](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.7B1...24n.7D). – Charles Duffy Apr 27 '20 at 15:28
  • BTW, it's also something that http://shellcheck.net/ will identify automatically. – Charles Duffy Apr 27 '20 at 15:29
  • BTW, note that all-caps variable names are used for names meaningful to the shell itself -- names with at least one lower-case character are reserved for application use, and are thus what you should use in your own code. And don't ever use `expr`; it'l a remnant of the 1970s; for every shell compatible with the 1991 POSIX sh standard, `reportnum=$(( reportnum + 1 ))` (after fixing the variable names, ofc) is preferred. (In bash specifically, one can also just use `(( ++reportnum ))`). See https://wiki.bash-hackers.org/scripting/obsolete – Charles Duffy Apr 27 '20 at 15:31
  • ...and see [the POSIX specification on environment variables](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html) re: the aforementioned naming convention guidelines -- relevant to regular non-exported shell variables as well because they share a namespace (setting a regular shell variable will overwrite any like-named environment variable). – Charles Duffy Apr 27 '20 at 15:32
  • Thanks, I ended up using the for loop example in the suggested solution. – Rob Holland Apr 28 '20 at 03:19

0 Answers0