Let me to tell you how you can have a nice calculator in your favorite shell (zsh).
In this particular instance I'm going to be using nushell as my fancy calculator, but this "trick" should work with other types of cli calculators.
What is this math mode?
While nushell is in this "mode" your basic math operators work like you would expect. What's so good about this? See, your regular shell treats symbols like *
, (
, )
in a way that doesn't have anything to do with math. In zsh
you can't do this:
(1 + 2) * 3
If we are talking about math, this won't do what you want to do. But in nushell the following is completely valid:
= (1 + 2) * 3
Notice that =
? That is what makes nushell go into this math mode, and it allow us to use parenthesis and multiply in a very nice way.
There is another interesting thing you need to know. In nushell we can do some math with a few time units. Something like this.
= 30min + 34min
These are duration units in nushell.
That will give you.
1hr 4min
I want that in my favorite shell.
Meet zcalc
For this to work you need nushell, so go get it.
After installing nushell we need to update our .zshrc
file. We are going to add a function.
zcalc() {
local args="$@"
nu -c "= $args"
}
Nothing fancy going on here. Just a function that gathers the arguments and gives it to nushell (in math mode). You can try it with simple stuff.
zcalc 1 + 2
That should work just fine. But this other thing won't.
zcalc 1 * 2
We are going to fix that using a precommand modifier called noglob
.
noglob zcalc 1 * 2
With noglob
things like *
are no longer expanded into filenames, there are just text. This gives us a nicer way of interacting with our calculator. Now let's turn this into an alias.
alias calc='noglob zcalc'
Math mode in zsh
But in nushell they have the =
thing. Can we have that in zsh
? Yes, but it does look kinda weird. Try doing this.
aliases[=]='noglob zcalc'
And now.
= 30min + (30min + 4min)
That works on my machine, your results may vary.
Show me the code
zcalc() {
local args="$@"
nu -c "= $args"
}
alias calc='noglob zcalc'
aliases[=]='noglob zcalc'
Conclusion
With this fancy trick you can now have a calculator for basic math. But not only that, this one has a nice interface that will let you forget about quoting your arguments. And if you use nushell it will even do (some) math with time units, and filesize units (mb, kb, all that stuff).
Thank you for your time. If you find this article useful and want to support my efforts, consider leaving a tip in ko-fi.com/vonheikemen.
Top comments (1)
For the people at home that don't want to use nushell, maybe you can try with
bc
.If you are interested in nushell and want to see an example config for that shell, here is my config.toml.