Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested shell variables without using eval

Tags:

bash

shell

eval

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})
like image 558
nachocab Avatar asked Jul 25 '11 15:07

nachocab


People also ask

Should I use eval in bash?

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.

How do you use variables in single quotes?

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.

What is the use of eval in bash?

`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.

What is Echo eval?

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)" .


1 Answers

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.

like image 66
Diego Sevilla Avatar answered Oct 04 '22 03:10

Diego Sevilla