Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append to an existing string variable inside a loop in bash? [duplicate]

Tags:

bash

I have a simple bash script that downloads stock prices and appends them to a variable, which is then outputted:

#!/bin/bash

output=" "
for stock in GOOG AAPL
do
  price=$(curl -s "http://download.finance.yahoo.com/d/quotes.csv?s=$stock&f=l1")
  output+="$stock: $price "
done

echo "$output"

This script only displays AAPL: 524.896, the last piece of data fetched. According to whatswrongwithmyscript, there isn't anything wrong with the script, and I thought I was following this answer properly. This answer discussed a similar problem (appending to a string variable inside a loop) and suggested a different method which I used like this:

#!/bin/bash

output=" "
for stock in GOOG AAPL
do
  price=$(curl -s "http://download.finance.yahoo.com/d/quotes.csv?s=$stock&f=l1")
  output="$output$stock: $price "
done

echo "$output"

The output is still the same. I'm using bash 4.2.45 on debian jessie x64.

More info

I echoed the result in a loop to debug, and from the first script, this is what I get:

 GOOG: 1030.42
 AAPL: 524.896
 AAPL: 524.896

And the second script gives the same thing:

 GOOG: 1030.42
 AAPL: 524.896
 AAPL: 524.896
like image 527
Michael A Avatar asked Mar 22 '26 21:03

Michael A


1 Answers

When I run your script and pipe the output to od -c, the result is illuminating:

0000000       G   O   O   G   :       1   0   3   0   .   4   2  \r    
0000020   A   A   P   L   :       5   2   4   .   8   9   6  \r      \n
0000040

So you can see that it IS in fact getting all the entries and concatenating them, but its ALSO getting CR characters (the \r in the od output), which causes them to print over the top of each other when you print the string.

You can pipe the output of curl to tr -d '\r' to strip off the problematic CRs:

price=$(curl -s "...." | tr -d '\r')
like image 124
Chris Dodd Avatar answered Mar 25 '26 10:03

Chris Dodd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!