nested shell variables without using eval

空扰寡人 提交于 2019-12-01 00:21:26

问题


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})

回答1:


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.




回答2:


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
final_es_sales_path
> current_database=${!current_database}
> echo $current_database
blahblah/es/sales.csv

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.




回答3:


Doesn't

current_database=${final_${country}_${action}_path}

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):

When braces are used, the matching ending brace is the first ‘}’ not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion.

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



来源:https://stackoverflow.com/questions/6818948/nested-shell-variables-without-using-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!