我的 shell 脚本似乎有点生疏了。我的愿望是在 bash 中循环一个 arraylist 配置变量,并使用在此循环中获得的必要参数调用一个函数,所有这些都无需分叉。
基本上,我创建了一个内部脚本人类可解析的逗号分隔配置变量,如下所示:
CONFIG="
0, 0x00, 'Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' %
1, 0x01, 'Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' %
51, 0x10, 'Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' %
63, 0xd4, 'Power up and unmute DAC' %
64, 0x00, 'Power up and unmute DAC' %
"
然后我想像这样循环它的参数:
while read reg val expl; do
printf "%s %s\n" "Calling i2c_write() with reg=${reg//,/}" \
"val=${val//,/} expl=$expl __EOL__";
# i2c_write() call
done <<< "${CONFIG//\%/$'\n'}"
当前输出为:
Calling i2c_write() with reg= val= expl= __EOL__
Calling i2c_write() with reg=0 val=0x00 expl='Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' __EOL__
Calling i2c_write() with reg= val= expl= __EOL__
Calling i2c_write() with reg=1 val=0x01 expl='Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' __EOL__
Calling i2c_write() with reg= val= expl= __EOL__
Calling i2c_write() with reg=51 val=0x10 expl='Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' __EOL__
Calling i2c_write() with reg= val= expl= __EOL__
Calling i2c_write() with reg=63 val=0xd4 expl='Power up and unmute DAC' __EOL__
Calling i2c_write() with reg= val= expl= __EOL__
Calling i2c_write() with reg=64 val=0x00 expl='Power up and unmute DAC' __EOL__
Calling i2c_write() with reg= val= expl= __EOL__
Calling i2c_write() with reg= val= expl= __EOL__
所需的输出将是:
Calling i2c_write() with reg=0 val=0x00 expl='Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' __EOL__
Calling i2c_write() with reg=1 val=0x01 expl='Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' __EOL__
Calling i2c_write() with reg=51 val=0x10 expl='Reset the chip, enable PLL with P=4, R=1, J=9, D=6338' __EOL__
Calling i2c_write() with reg=63 val=0xd4 expl='Power up and unmute DAC' __EOL__
Calling i2c_write() with reg=64 val=0x00 expl='Power up and unmute DAC' __EOL__
我很乐意用更合适的结构替换 CONFIG 变量,只要:
- a) 不需要分叉来遍历变量的条目,并且
- b) 人工解析和编辑所述变量的条目相当容易,并且
- c) 它适用于 bash 3.2.x 以上版本。