ampersander
ampersander

Reputation: 288

Bash syntax error when variable exceeds 1000000

I have a fairy simple script.

Here is a file:

>cat log1.txt
2021-07-29 16:58:47;MA;sell;1700.52;USD;606;65fae90c-7943-11eb-9726-8c85906a186d

Here is my script (it is supposed to multiply the value in the fourth column by the value in the sixth column):

File=`cat log1.txt`
profit+=`echo "$File" | awk -F\; '{ num1=$4+0;num2=$6+0;if($3 == "sell") { temp+=num1*num2 }else{temp-=num1*num2} } END {print temp}' | bc`

I came across some very unexpected behavior. As soon as the total profit exceeds 1 million, my script returns a syntax error. If the profit is below 1 million, it works.

Example of an input file that works

2021-07-29 16:58:47;MA;sell;1600.52;USD;606;65fae90c-7943-11eb-9726-8c85906a186d

Why is that? I've been pulling my hair out for hours now.

Upvotes: 0

Views: 78

Answers (1)

choroba
choroba

Reputation: 241978

The output of the awk command with the particular input is 1.03052e+06, but bc doesn't understand this format. Instead of printing the value, use printf in awk:

awk -F\; '{ num1=$4+0;num2=$6+0;if($3 == "sell") { temp+=num1*num2 }else{temp-=num1*num2} } END {printf "%d\n",temp}'

Upvotes: 1

Related Questions