I have d1="11"
and d2="07"
. I want to convert d1
and d2
to integers and perform d1-d2
. How do I do this in UNIX?
d1 - d2
currently returns "11-07"
as result for me.
I have d1="11"
and d2="07"
. I want to convert d1
and d2
to integers and perform d1-d2
. How do I do this in UNIX?
d1 - d2
currently returns "11-07"
as result for me.
An answer that is not limited to the OP's case
The title of the question leads people here, so I decided to answer that question for everyone else since the OP's described case was so limited.
TL;DR
I finally settled on writing a function.
0
in case of non-int:If you want to get a non-zero status code on non-int, remove the
||:
(aka ortrue
) but leave the;
Tests
Test output
Note
I got sent down this rabbit hole because the accepted answer is not compatible with
set -o nounset
(akaset -u
)The standard solution:
You can also do:
but beware that this will treat
07
as an octal number! (so07
is the same as7
, but010
is different than10
).Any of these will work from the shell command line.
bc
is probably your most straight forward solution though.Using bc:
Using
awk
:Using
perl
:Using
Python
:all return
Use this:
etc.
This should help.