bash - Bash:将变量存储在字符串中以便稍后解析
问题描述
这是代码的一小部分。我正在创建具有一个变量的 test_args,该变量需要稍后解决,当该变量在该范围内定义时,在这里,在一个 for 循环内。
test_args=""
test_args+='-test.coverprofile=/tmp/coverage${ii}.out'
test_dirs="a b"
ii=0
for d in ${test_dirs[@]}; do
echo ${test_args} # actually used as `go test ${test_args}`
ii=$((ii+1))
done
电流输出:
-test.coverprofile=/tmp/coverage${ii}.out
-test.coverprofile=/tmp/coverage${ii}.out
预期输出:
-test.coverprofile=/tmp/coverage0.out
-test.coverprofile=/tmp/coverage1.out
我愿意接受有关更好方法的建议。我需要使用不同的名称创建所有文件,以防止在循环中覆盖。
解决方案
使用eval
是通常的解决方案:
#!/bin/bash
test_args=""
test_args+='-test.coverprofile=/tmp/coverage${ii}.out'
test_dirs="a b"
ii=0
for d in ${test_dirs[@]}; do
eval echo ${test_args}
ii=$((ii+1))
done
结果是:
[user@linux ~]$ ./test2.sh
-test.coverprofile=/tmp/coverage0.out
-test.coverprofile=/tmp/coverage1.out
但这里有一个关于这个主题的有用讨论——我建议阅读左边链接的问题及其答案,尽管它并不完全适用于这个用例。
推荐阅读
- javascript - 在 codemirror 中提交表单后“onchange”不起作用
- javascript - 为什么在这个 JavaScript 示例中 shift 比索引访问更快?
- google-fit - Google fit API 配额和限制
- python - 如何为 closeEvent() 提供参数
- angular - TypeError:'this.validator is not a function' on complete not releated error callback
- xml - 在 JMeter 中签署 SAML AuthNRequest
- reactjs - 如何在firestore中上传pdf或doc等文件
- python-3.x - TypeError:NoneType 不可订阅 - IF 语句
- html - Sass mixin @content 不允许网格正常工作
- python - 将python列表转换为只有键的字典,没有值