首页 > 解决方案 > 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

我愿意接受有关更好方法的建议。我需要使用不同的名称创建所有文件,以防止在循环中覆盖。

标签: bashshell

解决方案


使用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

这里有一个关于这个主题的有用讨论——我建议阅读左边链接的问题及其答案,尽管它并不完全适用于这个用例。


推荐阅读