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

echo "4 * 5" | bc
  • 1
    Which shell are you using? – heavyd Jul 30 '15 at 20:15
  • 1
    Too many echos. – ctrl-alt-delor Jul 30 '15 at 20:16
  • 1
    bc <<< "4 * 5" – ctrl-alt-delor Jul 30 '15 at 20:17
  • 4
    Do you mean faster as in less keystrokes or as in lower execution time? – mpy Jul 30 '15 at 20:20
  • 1
    @mpy: less keystrokes – Texom512 Jul 30 '15 at 20:35
up vote 2 down vote accepted

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 :) – theoden Aug 2 '15 at 1:06

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.

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

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.