我需要把Bash命令的输出放到一个字符串变量中。
每个值之间用空格分隔。有很多选项可以做到这一点,但我不能使用mapfile
或read
选项(我使用Bash <</p>
这是命令的输出:
values="$(mycommand | awk 'NR > 2 { printf "%sn", $2 }')"
其中mycommand
只是一个云命令,可以获得以下值:
echo $values
mycommand输出:(我认为是一个以n结尾的字符串)对于每个值)
55369972
75369973
85369974
95369975
这就是我要做的:
在这里,我应该打印如下的值(我需要迭代变量values
,以便我可以单独打印每个值)。
期望的底层循环输出
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 "%sn", $2 }')"
# Replacing the new line with a space so I can iterate over each value
new_values="${values//$'n'/ }"
# new_values=("${values//$'n'/ }")
# Checking if I can print each value correctly
for i in "${new_values[@]}"
# for i in "$new_values"
do
echo "value: ${i}"
done
同样,我不能使用
# shellcheck disable=xxx
values=($(echo "${values}" | tr "n" " "))
当我检查代码时得到错误消息…
你知道我在代码中做错了什么吗?
try this:
#!/bin/bash
values="$(mycommand | awk 'NR > 2 { printf "%sn", $2 }')"
for v in $values; do
echo value: $v
done
用空格替换换行符的步骤将其呈现为字符串。如果你想把这个字符串分割成一个列表,你应该把它放在括号里(基于这个答案)
这应该是你所期望的:
# Getting the id field of the values
values="$(mycommand| awk 'NR > 2 { printf "%sn", $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'/ }")
是关键部分,那么您需要避免在迭代时将其放在引号中(或将其转换回字符串)
由于我不能将代码粘贴到评论中,所以我发布了一个答案,但功劳归于@akathimy。
这对我有用(解决方案#1):
#!/bin/bash
# Getting the id field of the values
values="55369972 75369973 85369974 95369975"
#
for v in $values; do
echo value: "$v"
done
和这个(解决方案#2):
#!/bin/bash
# Getting the id field of the values
values="55369972
75369973
85369974
95369975"
#
for v in $values; do
echo value: "$v"
done
编辑那这个(解决方案3)呢?:
#!/bin/bash
# Getting the id field of the values
values=("55369972
75369973
85369974
95369975")
#
for v in ${values[@]}; do
echo value: "$v"
done
最后一条适用于我,也许也适用于你。让我知道。