inside the mind of a linux admin

Advanced Bash Scripting: variable within a variable

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.

Related Posts

synergy: How to enable crypto (encryption) and generate SSL certificate

The newer Linux versions of the popular mouse/keyboard sharing application “synergy” now has built in encryption. Here’s how to configure it: Just simply passing the –enable-crypto flag on your synergy server without having a proper SSL certificate will result in the inability to connect to clients and generate an error message similar to this in […]

Read More

Change Number Pad Delete (dot) key from a comma in Ubuntu Linux

I recently purchased a new keyboard and updated to the latest Ubuntu, I’m also an avid user of the number pad for quick input when dealing with spreadsheets or accounting. I found that my num pad’s delete key (“.”) was outputting a comma (“,”) instead. Pretty annoying? I agree, but this can be very easily […]

Read More

1 Comment

  • Grant McWilliams on Monday, July 11, 2011

    Don’t we refer to this as an indirect variable reference?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.