2
Is there a faster way to calculate in command line the following:
echo "4 * 5" | bc
2
Is there a faster way to calculate in command line the following:
echo "4 * 5" | bc
2
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.
This also works in case of fizsh
, that's close :) – theoden8 – 2015-08-02T01:06:56.047
4
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.
2
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.
Lol, never thought of it. – theoden8 – 2015-07-30T20:22:13.147
That isn't work with fish shell... – Texom512 – 2015-07-30T20:47:04.073
This is bash shell – glenn jackman – 2015-08-02T00:59:24.177
1Which shell are you using? – heavyd – 2015-07-30T20:15:05.307
1Too many
echo
s. – ctrl-alt-delor – 2015-07-30T20:16:12.0001
bc <<< "4 * 5"
– ctrl-alt-delor – 2015-07-30T20:17:23.8404Do you mean faster as in less keystrokes or as in lower execution time? – mpy – 2015-07-30T20:20:54.923
@heavyd: I use Fish Shell. – Texom512 – 2015-07-30T20:34:29.090
1@mpy: less keystrokes – Texom512 – 2015-07-30T20:35:22.060