Search code examples
linuxunixwindows-subsystem-for-linuxbc

How can I use brackets while using bc (Unix basic calculator)?


While working with bc, UNIX basic calculator on my Ubuntu WSL, I found this bizarre behaviour:

Prompt> echo (1+2)*3 | bc -l
-bash: syntax error near unexpected token `1+2'
Prompt> echo (1 + 2) * 3 | bc -l
-bash: syntax error near unexpected token `1'

At first, I thought this meant that bc does not cover brackets, but then I did this:

Prompt> bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
(1 + 2) * 3
9
(1+2)*3
9
^C
(interrupt) use quit to exit.
quit

So bc does support the usage of brackets.

Does anybody know how I can use arithmetic expressions with brackets, while using bc as a one-liner-support-tool (I mean, while using it in one-liners like (...| bc)?

In the meantime I've understood that the usage of bc can be easily replaced with $((...)), so in order to calculate (1+2)*3 in a UNIX prompt, I can use the following command:

echo $(( (1+2)*3 ))

Please reopen the question, so that I can add this latter as an answer for reference purposes.


Solution

  • Use quotes around your expression, such as:

    echo "(1 + 2) * 3" | bc -l