ᴜsᴇʀ
ᴜsᴇʀ

Reputation: 1158

Explanation of bash calculator code

Can someone explain me this bash code?

read text && echo $text | bc -l

Thanks!

Upvotes: 1

Views: 216

Answers (1)

MillaresRoo
MillaresRoo

Reputation: 3848

To be brief: read user input, pass it to bc command and output its result.

More on bc command: http://www.gnu.org/software/bc/manual/html_mono/bc.html

Step by step explanation:

read text && echo $text | bc -l

read text Reads a line from the standard input and saves it in the text variable.

&& Lets you do something based on whether the previous command completed successfully.

echo Display message to the standar output.

$text Retrieves the value of the text variable.

| A pipe lets you use the output of a program as the input of another one

bc -l bc is an arbitrary precision calculator language. -l is an option defining the standard math library.

So, the full code:

  1. Reads a line from the standard input (keyboard) and saves it to a variable named text
  2. Outputs the value of the text variable to bc
  3. If the user input contains a mathematical expression, bc will return the result.

Usage:

$ read text && echo $text | bc -l
(3+3)*2 <-- user input containing a mathematical expression
12      <-- result

Upvotes: 6

Related Questions