Take the 2-minute tour ×

Can I get rid of eval here? I'm trying to set $current_database with the appropriate variable determined by user input (country and action)

# User input

# Possible variables for current_database

current_database=$(eval echo \${final_${country}_${action}_path})
share|improve this question
Just a note: en, es, it are language codes (ISO 639-1), not country codes. Country codes (ISO 3166-1) look like this: ES, MX, GB, US, IT (to name some countries where these languages are spoken). –  Paŭlo Ebermann Jul 25 '11 at 16:20

3 Answers 3

up vote 8 down vote accepted

You can use associative arrays, joining the value of both variables. For example:

declare -A databases
# initialization

Then, you can get the database just by:

echo ${databases["${country}:${action}"]}

This has the advantage of having the database names collected by only one variable.

share|improve this answer
Nice. So I can just do: current_database=${databases["${country}:${action}"]}. I wonder if there's also a way to do it in Bash 3.x –  nachocab Jul 25 '11 at 16:41

Actually, yes you can, and without resorting to associative arrays (which isn't a bad solution, mind you). You can use a solution similar to this:

> current_database=$(echo final_${country}_${action}_path)
> echo $current_database
> current_database=${!current_database}
> echo $current_database

This avoids arrays and evals by using indirect expansion. This appears to have been introduced in the second version of Bash, so pretty much any machine should be able to do it.

share|improve this answer



do what you want?

Edit: No, it does not. Parameter expansion works only on one word (for the parameter name), and $ is not allowed in a word. It would be possible to use nested parameter expansion in the other parts of the more complicated versions (with limits, replacement, default value etc.), though, which is why the several expansion variants are listed here (which fooled me first) (emphasis by me):


Sorry. Looks like eval and arrays are your best bet, then.

share|improve this answer
No, it's a bad substitution. ${final_${country}_${action}_path}: bad substitution –  nachocab Jul 25 '11 at 16:32

Your Answer


