Shell course Lesson 3 of 6

Shell from zero: a number is still text until you ask

A variable that looks like a number is text. $((cents * 2)) evaluates it as arithmetic. The program stores 450 and prints 900.

Zara is one of GoByte's characters. This post was drafted by AI agents in Zara's voice, then fact checked, run and edited by the GoByte team.

Back to top

cents=450 stores the characters 4, 5, and 0. echo "$cents" prints them. Nothing has added anything. $(( ... )) is the request to read that text as a whole number and do arithmetic. Two lattes are 900 cents. The result is text again, digits you can print.

Arithmetic is a mode, not a type#

cents=450 stores three characters. Nothing about the variable becomes numeric. $((cents * 2)) is a different parsing mode: names inside it are read as integers, the arithmetic runs, and the result is converted back to text for echo. You write cents there, not $cents. The spaces around * are allowed in that mode and forbidden around the = of an assignment. A non-numeric value becomes 0 in this mode, quietly. If cents were the word latte, $((cents * 2)) would print 0. $((5 / 2)) is 2, because the arithmetic is integer only.

The characters 450, read as cents once
  1. cents450
  2. cents * 2900
cents=450
echo $((cents * 2))
900

The double parentheses are the arithmetic#

cents * 2 inside $(( )) is 900, the cents for two lattes. You do not write $cents inside the arithmetic. The name cents is enough. Outside, you need $cents or "$cents". The spaces around * are fine here. They are not fine around the = of an assignment.

cents=latte and then $((cents * 2)) does not produce a useful product. The shell treats a value that is not a number as 0 in this context, so the print is 0. That quiet zero is why you confirm the contents before you calculate. Print "$cents" when a total looks wrong.

Integer arithmetic only#

$((5 / 2)) is 2. The fraction is dropped, the same tip as in the Java lesson. The shell's $(( )) does not have floats. A price in cents can live here as a whole number. 450 cents doubled is 900 cents, which is $9.00 when you format it. A price in dollars and cents belongs in cents until you format it. The next lesson wraps that formatting in a function you can call by name.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.