Maths in the shell

I’ve been using “expr” in sh/csh/ksh and bash for decades to do simple integer maths in shell scripts and interactively…

But then about 2-3 years ago realised didn’t need “expr” - Bash can do maths (I’m not from North America, and the word “math” sounds kinda naff to my ears, it sounds like someone with a lisp talking about “mass” - which to a former Catholic like myself, is anathema - e.g. “We go to math every Thunday” :smiley: ) “out of the box”

e.g.

echo $((2019-1945))
74

or

export SINCE_WW2=$((2019-1945))
echo $SINCE_WW2
74

and - I always thought to do floating point, had to use “bc” which I kinda hate (reminds me of Comp Sci lecturers extoling the virtues of the Reverse Polish Calculator)…

So - I took a look at my camelface script “mon-xfer.bash” - which I’d written back in December 2018 to monitor an rsync backup I was making of my NAS ( to 6 TB external USB ) because I’d screwed up my zpool on there (added replacement disk as a stripe member, a “concat” instead of raidz+ member) and realised I used some awk to do some simple floating point calcs… no need to break out “bc”…

e.g.

awk "BEGIN {print (365/7)"
52.1429

or

export WEEKSPA=$(awk "BEGIN {print (365/7)}")
echo $WEEKSPA
52.1429

The more I learn about sed and awk, the more I realise how little I know :smiley: (and I’ve been using them rudimentarily for probably decades - even read bits and pieces of the O’Reilly book too). There’s probably neater and more elegant/efficient ways of doing floating point arithmetic in the shell - but I’d rather use awk than bc…

2 Likes

I’ve had good experience with spigot.

1 Like

You yet is a man of middle-age to worry
with these genre calculations, best to use
Linux desktop ( gui ) calculator, have a nice day :wink:

i’m not sure i understand?

Only joke, nothing more :smile:

1 Like

i just wanted to make sure. i appreciate you clarifying that for me :slight_smile:

totally not adding to the converstion, but: as an american i always thought maths sounded way more formal like what Stephen Hawking would get up to in his spare time. the only time i figured singular math was better was when addressing mathletes, because mathsletes just sounds weird to me :smiley:

1 Like

BTW - “camelface” script - still shows a camelface (which also looks a bit like a cameltoe) icon in Nautilus, to this day, and I’ve no idea why it especially gets a different Nautilus icon than all my other shell scripts :

image