Bash 从文件中读取值以设置变量

时间:2021-03-05 15:12:42

标签: bash

我正在尝试清理我的一些代码,以删除我通过软重启和硬重启来运行测试和监控日志的大量重复代码。

我拥有的脚本将循环执行 7 组测试并将结果输出到 /persist/ 目录中的各个文件夹。我有一个文件,它只包含一个 1-7 的整数来记录我在哪个测试阶段(必须通过重新启动来保持)

/persist/whichtest

以下测试/文件夹位于 /persist/ 中,以便我的结果进入

Boot
stress
swap
longevity
gps
platform
gpslong

我将如何根据 /persist/whichtest 中设置的数字将“${testname[i]}”设置为等于我的测试名称之一?

所以每次执行Boot中的测试时,都会将结果输出到/persist/Boot,而当执行gps的测试时,结果会去{{1} }}

/persist/gps
function logs {
  echo "insertlog stuff here" >> /persist/"${testname[i]}"/test1.log
  echo "insertlog stuff here" >> /persist/"${testname[i]}"/test2.log
  echo "insertlog stuff here" >> /persist/"${testname[i]}"/test3.log
}

当它运行第一轮测试时,结果将进入declare -a testname=(Boot stress swap longevity gps platform gpslong)

当它运行第二轮测试时,结果将进入/persist/Boot/

然后对每个测试用例遵循相同的模式

这是我想要使用的功能

/persist/stress/

我遇到了一些障碍,因此感谢您提供任何建议。

编辑了我原来的问题,抱歉,措辞不太好。希望这能让事情变得更清楚。

Full script is here

3 个答案:

答案 0 :(得分:0)

您可以使用关联数组(就像许多其他语言的字典一样):

testname=( ["1"]="A" ["2"]="B" ["3"]="C" )
echo "${testname[1]}"

这将输出 A

答案 1 :(得分:0)

您可以在循环中添加一个计数器。

Navigator.of(context).push(MaterialPageRoute(builder: (context) => UiViewProfile(e)));

输出

${__javaScript(encodeURIComponent("${myVar}"),)}

如果没问题,那么使用关联数组。只需在循环内声明即可。

testname=(a b c d e f g)
n=1
for f in "${testname[@]}"; do
  printf '%d %s\n' "$((n++))" "$f"
done

输出

1 a
2 b
3 c
4 d
5 e
6 f
7 g

查看 bash 手册的 Groovy 部分。 还有array

答案 2 :(得分:0)

其他回答者似乎忽略了问题是关于从文件中读取值以设置变量。您已经声明的 testname 数组,但如果 数字从 1-8 缺少 h。将文件内容插入命令的便捷 Bash 语法是 $(<...),因此您可以使用 ii=$(</persist/whichtest)-1 设置为所需的索引。减 1 是必要的,因为数组索引从 0 开始。(当然,减法仅在 ${testname[i]} 索引括号内计算。)

相关问题