将 for 循环结果存储为 bash 中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36223802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:24:58  来源:igfitidea点击:

Store for loop results as a variable in bash

linuxbashfor-loop

提问by Tony

I have a loop similar to the following:

我有一个类似于以下的循环:

for time in ${seconds_list}; do
    echo "scale=2; (${cur_time}-${time})/3600" | bc
done

Of course, I could "echo" the results to a file and be done with it, but I think a more elegant approach would be to store all the for-loop results in one variable, that I could use at a later time. The variable containing all results would have to look something like this:

当然,我可以将结果“回显”到一个文件中并完成它,但我认为更优雅的方法是将所有 for 循环结果存储在一个变量中,我可以在以后使用。包含所有结果的变量必须如下所示:

var='30.25
16.15
64.40
29.80'

Is there an easy way in which I can achieve this?

有没有一种简单的方法可以实现这一目标?

回答by Stefano d'Antonio

It's really easy, you can just redirect the output of the whole loop to a variable (if you want to use just one variable as stated):

这真的很简单,您只需将整个循环的输出重定向到一个变量(如果您只想使用一个变量):

VARIABLE=$(for time in ...; do ...; done)

your example:

你的例子:

var=$(for time in ${seconds_list}; do
          echo "scale=2; (${cur_time}-${time})/3600" | bc
      done)

Just enclosing your code into $().

只需将您的代码包含在 $() 中。

回答by anubhava

Better to use a BASH array to store your results:

最好使用 BASH 数组来存储您的结果:

results=()

for time in ${seconds_list}; do
    results+=($(bc -l <<< "scale=2; ($cur_time-$time)/3600"))
done

# print the results:

printf "%s\n" "${results[@]}"