【发布时间】:2023-01-12 17:08:05
【问题描述】:
我需要将 Bash 中命令的输出放入字符串变量中。
每个值应以空格分隔。有很多选项可以做到这一点,但我不能使用mapfile或read选项(我在 macOS 中使用 Bash < 4 版本)。
这是命令的输出:
values="$(mycommand | awk 'NR > 2 { printf "%s\n", $2 }')"
echo $values
输出:
55369972
75369973
85369974
95369975
这就是我想要做的:
在这里我应该打印像这样的值
value: 55369972
value: 75369973
value: 85369974
value: 95369975
但我得到这个:
value: 55369972 75369973 85369974 95369975
# Getting the id field of the values
values="$(mycommand| awk 'NR > 2 { printf "%s\n", $2 }')"
# Replacing the new line with a space
new_values="${values//$'\n'/ }"
# Checking if I can print the values correctly
for i in "${new_values[@]}"
do
echo "value: ${i}"
done
知道我在代码中做错了什么吗?
【问题讨论】:
-
计算为
new_values="${values//$'\n'/ }"的变量new_values是一个字符串,而不是数组。对其假定的元素进行迭代是没有意义的。