Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store for loop results as a variable in bash

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:

var='30.25
16.15
64.40
29.80'

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

like image 966
Tony Avatar asked Mar 25 '16 16:03

Tony


2 Answers

Better to use a BASH array to store your results:

results=()

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

# print the results:

printf "%s\n" "${results[@]}"
like image 106
anubhava Avatar answered Oct 04 '22 13:10

anubhava


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 $().

like image 40
Stefano d'Antonio Avatar answered Oct 04 '22 14:10

Stefano d'Antonio