【问题标题】:Print string variable that stores the output of a command in Bash打印在 Bash 中存储命令输出的字符串变量
【发布时间】:2023-01-12 17:08:05
【问题描述】:

我需要将 Bash 中命令的输出放入字符串变量中。

每个值应以空格分隔。有很多选项可以做到这一点,但我不能使用mapfileread选项(我在 macOS 中使用 Bash < 4 版本)。

这是命令的输出:

values="$(mycommand | awk 'NR &gt; 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 是一个字符串,而不是数组。对其假定的元素进行迭代是没有意义的。

标签: bash macos


【解决方案1】:

尝试这个:

#!/bin/bash

values="$(mycommand | awk 'NR > 2 { printf "%s
", $2 }')"
for v in $values; do
  echo value: $v
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2014-11-09
    • 1970-01-01
    • 2012-04-03
    • 2015-11-08
    • 1970-01-01
    相关资源
    最近更新 更多