是的,是的,我知道你可能会说“嘿,还有成百上千的人在问同样的问题”,但那不是真的,我不想做这样的事情:
foo="example1"
bar="example2"
foobar="$foo$bar"我想这么做:
foo="example1"
$foo="examle2"但是,每当我尝试这样做时,我都会收到一条错误消息,上面写着:
bash: example1=example2: command not found有什么建议吗?这有可能吗?
发布于 2018-08-22 20:07:51
下面是一些示例:
declare [-g] "${foo}=example2"declare -n foo='example1'
foo='example2'eval "${foo}=example2"mapfile -t "${foo}" <<< 'example2'printf -v "${foo}" '%s' 'example2'IFS='' read -r "${foo}" <<< 'example2'typeset [-g] "${foo}=example2"正如其他用户所说,对eval和一般的间接分配要小心。
发布于 2018-08-22 19:39:09
使用eval是可能的。
eval $foo="examle2"请注意,您应该非常确信$foo的值是可信的。
另一种更好的选择是使用索引数组,在这种情况下,您不会冒险执行任意命令。
发布于 2018-08-22 19:40:41
suffix=bzz
declare -g prefix_$suffix=mystr然后...and ..。
varname=prefix_$suffix
echo ${!varname}无耻地从这里偷来的。
编辑:正如Stephane所说,这通常是个坏主意,应该避免。索引数组是更好的选择。
https://unix.stackexchange.com/questions/464225
复制相似问题