这里是我的问题的最简单的蒸馏版本。即使在这里不是很明显,仍然存在的复杂性是有充分理由的。另外脚本是内部的,没有执行恶意代码的机会,所以eval是完全正确的;不需要知道它是多么邪恶......;)暂时假定键字符串中的管道和冒号是必需的分隔符。bash,eval,保护管道和冒号字符串
key="target|platform|repo:revision"
hashname="hashmap"
declare -A $hashname
eval $hashname[$key]=0
echo $(eval $hashname[$key])
当然,最后两行有问题,因为eval作用于$ key变量的管道和冒号。我的问题是如何从eval保护这样的字符串?我需要eval,因为我指的是hashmap的名称而不是它本身。提前致谢。
============================================== ====================================
好吧我其实开始认为我的问题是不是与管道和冒号和eval。所以让我贴实际的代码
function print_hashmap()
{
local hashname=$1
for key in `eval echo \$\{\!$hashname[@]\}`; do
local deref="$hashname[$key]"
local value=${!deref}
echo "key=${key} value=${value}"
done
}
function create_permutations2()
{
local hashname=$1 ; shift
local builds=$1 ; shift
local items=$1 ; shift
local [email protected]
echo "create_permutations(hashname=${hashname}, builds=${builds}, items=${items}, separators=${separators})"
if [ NULL != "${builds}" ]; then
for build in `echo $builds | tr ',' ' '`; do
local target="${build%%:*}"
local platforms="${build##*:}"
for platform in `echo $platforms | tr '|' ' '`; do
local key=
local ref=
if [ NULL != "${items}" ]; then
if [ NULL == "${separators}" ]; then separators=' '; fi
for separator in $separators; do
items=`echo $items | tr $separator ' '`
done
for item in $items; do
key="${target}|${platform}|${item}"
ref="$hashname[$key]"
declare "$ref"=0
done
else
key="${target}|${platform}"
ref="$hashname[$key]"
declare "$ref"=0
fi
done
done
fi
echo "created the following permutations:"
print_hashmap $hashname
}
builds="k:r|s|w,l:r|s|w"
repos="c:master,m:master"
hashname="hashmap"
declare -A $hashname
create_permutations2 $hashname $builds $repos ","
print_hashmap $hashname
我最近修改了代码FatalError的建议使用参考,而不是EVAL和错误,以符合是相同的:在表达式语法错误(错误标记附近:主)
你有没有试过逃脱管道字符?例如:'\ |'而不是'|' – Gigi 2012-02-05 19:03:52
是的;那不起作用 – 2012-02-05 19:21:27
你想做什么?这不是你如何访问数组成员 – Kevin 2012-02-05 19:29:29