← Linux and the Command Line Lesson 43 of 51 · 10 XP

Data types: strings and numbers

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

In shell everything is a string. A string becomes a number only inside arithmetic:

a=5
b=3
echo "$a + $b"            # 5 + 3 — just text
echo $((a + b))           # 8   — arithmetic expansion
echo $((a * b)) $((a / b)) $((a % b))    # 15 1 2 — the division is integer division!
c=$((a ** 2))             # 25 (in bash and BusyBox; plain POSIX sh has no power operator)

Inside $(( )) you can leave out the $ before names.

The shell doesn't know fractional numbers. For them, bc or awk is used:

echo "scale=2; 10 / 3" | bc       # 3.33
awk 'BEGIN { printf "%.2f\n", 10 / 3 }'

To check that a string is an integer:

case $x in
    ''|*[!0-9]*) echo "not a number" ;;
    *)           echo "a number" ;;
esac

bash has real arrays (arr=(a b c), ${arr[1]}). POSIX sh and BusyBox don't: they use the positional parameters set -- a b c and $1 $2 $3, or strings separated by spaces.

Task. Read two integers (on one line). Print their sum, difference, product, integer quotient and remainder — each on its own line. On the last line, print the result of ordinary division with two decimal places (with awk).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.