Hi All;
I have 2 variable let's say $A and $B. These are actually some remotely executed command outputs. I captured these values in my local variables. Here is my problem. When I try to do some arithmetic operation with these variables, I receive an error message. Neither expr nor typeset -i commands worked for me. When I try to add them I receive this:
echo $A
809189640755
echo $B
1662145726
sum=`expr $B + $A`
expr: non-integer argument
sum=$(( $B + $A ))
")809189640755: invalid arithmetic operator (error token is "
typeset -i A
A=$A
")syntax error: invalid arithmetic operator (error token is "
So what is the best way to convert a string variable into a numeric variable in bash?
It looks like the commands you're using to set A and B are adding trailing carriage returns.
You can get rid of them (and any other non-numeric characters) with:
A=$(printf "%s" "$A"|tr -dc '[:digit:]')
B=$(printf "%s" "$B"|tr -dc '[:digit:]')
1 Like
This may also work in bash/ksh without using sub-shells or external commands:
A=${A//[^[:digit:]]/}
B=${B//[^[:digit:]]/}
Edit: After some testing on ksh, it seems this method fails on some ksh implementations.
It looks like the commands you're using to set A and B are adding trailing carriage returns.
You can get rid of them (and any other non-numeric characters) with:
A=$(printf "%s" "$A"|tr -dc '[:digit:]')
B=$(printf "%s" "$B"|tr -dc '[:digit:]')
This worked for me. Thanks a lot.