如何将 for 循环的输出存储到变量

Ama*_*kon 2 shell for variable

我有以下外壳代码:

for value in 10 5 27 33 14  25
do
      echo  $value
done
Run Code Online (Sandbox Code Playgroud)

但是如果我想稍后操纵输出怎么办?我想将整个输出存储在一个变量中。这可能吗?

Sté*_*las 6

for循环与任何其他命令没有什么不同,您可以使用命令替换:

variable=$(
  for value in 10 5 27 33 14  25
  do
    echo "$value"
  done
)
Run Code Online (Sandbox Code Playgroud)

将整个输出减去最后一个添加的最后echo一个换行符作为字符串存储到标量$variable变量中。

然后你会这样做:

printf '%s\n' "$variable" | further-processing
Run Code Online (Sandbox Code Playgroud)

或者:

futher-processing << EOF
$variable
EOF
Run Code Online (Sandbox Code Playgroud)

在bashshell 中,您还可以使用以下命令将输出的每一行存储到数组的元素中:

readarray -t array < <(
  for value in 10 5 27 33 14  25
  do
    echo "$value"
  done
)
Run Code Online (Sandbox Code Playgroud)

要将输出的每个空格/制表符/换行符分隔的单词(假设为默认值$IFS)存储到数组中,可以使用 split+glob 运算符,并禁用 glob 部分

set -o noglob # not needed in zsh which does only split upon unquoted
              # command substitution. zsh also splits on NULs by default
              # whilst other shells either removes them or choke on them.
array=(
  $(
    for value in 10 5 27 33 14  25
    do
      echo "$value"
    done
  )
)
Run Code Online (Sandbox Code Playgroud)

使用zsh/ bash/ ksh93,您还可以执行以下操作:

array=()
for value in 10 5 27 33 14 25
do
  array+=( "$(cmd "$value")" )
done
Run Code Online (Sandbox Code Playgroud)

来构建阵列。

然后在所有这些中,你会这样做:

further-processing "${array[@]}"
Run Code Online (Sandbox Code Playgroud)

要将数组的所有元素作为参数传递给futher-processingor:

printf '%s\n' "${array[@]}" | further-processing
Run Code Online (Sandbox Code Playgroud)

要将每个元素打印在一行上,通过管道传输到further-processing

但请注意,如果数组为空,仍然会打印空行。您可以通过使用print -rC1 --而不是printf '%s\n'在zsh任何类似 Bourne 的 shell 中或在任何类似 Bourne 的 shell 中定义一个函数来避免这种情况,例如:

println() {
  [ "$#" -eq 0 ] || printf '%s\n' "$@"
}
Run Code Online (Sandbox Code Playgroud)