0

When I try to calculate a maths problem such as 1 + 1 using the Ubuntu console like this:

user@servername:~$ 1 + 1

Ubuntu thinks the first 1 is a command and I get this error:

1: command not found

I then tried to use echo to evaluate the string (with and without quotes) like this:

user@servername:~$ echo 1 + 1
user@servername:~$ echo "1 + 1"

Unfortunatly both output 1 + 1 and not 2.

It would also be greatly appreciated to include a explanation as to why echo does not evaluate the specified string before outputting it?

Also is there is a built-in command that evaluates a string before outputting it (maybe something that behaves like eval in Python)?

Thank you for the help in advance.

2 Answers2

3

The one I usually use is

bc<<<2+2

You can make that easier to type with an alias:

$ alias x='bc<<<'
$ x 53*(27-23)
212

If you put whitespace in the expression you'll need to quote it. Also if the expression starts with an open parenthesis (as opposed to having one in the middle).

rici
  • 234,347
  • 28
  • 237
  • 341
2
$ echo $((1+1))
2

$ echo "1+1" | bc
2

$ awk 'BEGIN{print 1+1}'  
2
karakfa
  • 66,216
  • 7
  • 41
  • 56
  • Thank you for the answer I appreciate it, but I don't understand the difference between each method, could you please explain it? –  Feb 27 '16 at 17:15
  • first one shell does the computation, second is the `bc` calculator, third one is the `awk` script. For simple integer arithmetic first one is fine and third one is the most flexible if you need formatting, if-then-else logic etc. `bc` is the most common one, for floating point you need to use the `-l` option, otherwise answers will be truncated to int. – karakfa Feb 27 '16 at 21:47