Tutankhamen
Tutankhamen

Reputation: 3562

evaluate program output as an integer in bash

I have an application which outputs a string with a number, like this:

output number is 20.

I have a code which parses output and cutting out only the number:

result=$(./my_script | awk 'print $4')
echo $result

the result output will be "20" as expected, but now, if I would try to use it as an integer, for example:

result=$((result+1))

then I will get an error:

13915: syntax error: operand expected (error token is "20")

Using it as a seq argument will also give an error

$(seq 0 $result) 
seq: invalid floating point argument: ‘\033[?25h\033[?0c20’

trying to print it with %q will give the same result:

printf '%q' $result
'\E[?25h\E[?0c20'

So, it looks like there are some unexpected characters in the string, but I'm not sure how to trim them?

Thank you!

Upvotes: 1

Views: 2352

Answers (2)

Diego Torres Milano
Diego Torres Milano

Reputation: 69228

Or, simply, change the field separator

result=$(./my_script | awk -F '[. ]' '{print $4}')
echo $result

Upvotes: 0

z3nth10n
z3nth10n

Reputation: 2451

You can try to get the number by using Regex.

It worked for me:

#!/bin/bash

result=$(bash output.sh | sed 's/[^0-9]//g')
r=$((result+1))
echo $r

Hope this helps.

Upvotes: 3

Related Questions