Is there a faster way to calculate in command line the following:
echo "4 * 5" | bc
I'd like to add a solution for the Z shell, unfortunately I know almost nothing about fish, so that I could adapt this for fish syntax. Sorry!
I define a funcion c
:
function c { echo $@ | bc }
And I set an alias for c
, so that no file globbing takes place (and I can omit the quotes around expressions especially including a star:
alias c="noglob c"
Then I can do calculations like this:
$ c 4*5
20
$ c 1.5*2^8
384.0
That are 3 keystrokes (including the final ENTER
) more than the actual expression to be calculated. Can be improved... perhaps with keybindings.
POSIX-compatible Shells (dash
ksh
bash
zsh
and many more)
There's a built-in method for that. Use $(())
construction to do it:
echo $((4 * 5))
It does not call any functions, so it's faster.
Let's compare the ways (zsh
):
$ time ( echo "4 * 5" | bc )
20
( echo "4 * 5" | bc; ) 0.00s user 0.00s system 61% cpu 0.007 total
$ time ( echo $((4 * 5)) )
20
( echo $((4 * 5)); ) 0.00s user 0.00s system 48% cpu 0.001 total
However, $(())
has a lot of restrictions and is capable to do only basic arithmetical operations.
C Shells (csh
tcsh
)
I don't think there is a one-expression solution in C Shells. However, it is possible to do the following:
@ i = 4 * 5 ; printf "$i\n"
Fish
Probably, math "4 * 5"
works faster.
A more general answer than the better (in this case) $(( ))
answer is to use <<<
e.g. bc <<< "4 * 5"
Here we don't need to use echo
, we just send the argument into stdin.
echo
s.bc <<< "4 * 5"