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
country="es"
action="sales"
# Possible variables for current_database
final_es_sales_path="blahblah/es/sales.csv"
final_en_support_path="yadayada/en/support.csv"
final_it_inventory_path="humhum/it/inventory.csv"
...
current_database=$(eval echo \${final_${country}_${action}_path})
In the Bash programming language, the eval built-in has a wide range of applications. That is, it can execute other commands, set shell environment, and perform variables substitution and indirection. However, such a powerful tool should be used with care.
Single quotes:When you enclose characters or variable with single quote ( ' ) then it represents the literal value of the characters. So, the value of any variable can't be read by single quote and a single quote can't be used within another single quotes.
`eval` command is used in bash to execute arguments like a shell command. Arguments are joined in a string and taken as input for the shell command to execute the command. `eval` executes the command in the current shell.
eval echo \${$n} runs the parameters passed to eval . After expansion, the parameters are echo and ${1} . So eval echo \${$n} runs the command echo ${1} . Note that most of the time, you must use double quotes around variable substitutions and command substitutions (i.e. anytime there's a $ ): "$foo", "$(foo)" .
You can use associative arrays, joining the value of both variables. For example:
declare -A databases
# initialization
databases["es:sales"]="blahblah/es/sales.csv"
databases["en:support"]="yadayada/en/support.csv"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With