Many folks will know this in many other programming languages (C, C++, etc) as a “pointer”, but what if you’re a bash kid at heart and you want to define a variable within a variable?
I encountered this exact quandary today while coding a pretty sophisticated script which reaches back into the past for data. The script would simply take the current day and subtract to go “back in time”. The problem arose in the beginning of the month, when reaching back 4 days from the 3rd would give you a value of -1. I coded a workaround, using standardized variables with incremental numbers and a for loop. At that point, I had to find a way to tell the called function that if we’re in a day that’s “-lt 10” (less than 10) to be a tad bit smarter.
for TIMETRAVEL in {1..8}
do
getdaydata $TIMETRAVEL
done
So, the $TIMETRAVEL variable is going be 1 through 8 (1,2,3,4,5,6,7,8). The function “getdaydata” is getting passed each number between 1 and 8. The function then needed to take this data and formulate a new variable “pointing” to the previously defined variable. It took a bit of fiddling, but here’s how I did it:
eval HISTMONTH=\$BACK${TIMETRAVEL}MON
eval HISTDAY=\$BACK${TIMETRAVEL}DAY
Using eval, I’m able to build and define “$HISTMONTH” and “$HISTDAY” with previously defined variables within the getdaydata() function.
Tweet
Don’t we refer to this as an indirect variable reference?