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?
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[@]}"
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 $().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With