2

Is there a faster way to calculate in command line the following:

echo "4 * 5" | bc
6
  • 1
    Which shell are you using?
    – heavyd
    Jul 30, 2015 at 20:15
  • 1
    Too many echos. Jul 30, 2015 at 20:16
  • 1
    bc <<< "4 * 5" Jul 30, 2015 at 20:17
  • 4
    Do you mean faster as in less keystrokes or as in lower execution time?
    – mpy
    Jul 30, 2015 at 20:20
  • 1
    @mpy: less keystrokes
    – Texom512
    Jul 30, 2015 at 20:35

3 Answers 3

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.

1
  • This also works in case of fizsh, that's close :)
    – theoden8
    Aug 2, 2015 at 1:06
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.

3
  • Lol, never thought of it.
    – theoden8
    Jul 30, 2015 at 20:22
  • That isn't work with fish shell...
    – Texom512
    Jul 30, 2015 at 20:47
  • This is bash shell Aug 2, 2015 at 0:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .