# shell - using expr “multiplication table”

I'm learning shell to create a multiplication table, I write code like that:

``````#!/ in/bash

for i in 1 2 3 4 5 6 7 8 9

do

for j in 1 2 3 4 5 6 7 8 9
do
if [ \$j -le \$i ]
then
echo -ne "\$i"X"\$j"=`expr "\$i"*"\$j"` "\t"
else
echo
break
fi
done
done
echo -ne "\n"
``````

however I get the response in console like that:

``````1X1=1*1
2X1=2*1         2X2=2*2
3X1=3*1         3X2=3*2         3X3=3*3
4X1=4*1         4X2=4*2         4X3=4*3         4X4=4*4
...
``````

I hope the answer is like that "1x1=1, 2x1=2 ...". Could anyone tell me how to modify this code?

• Or put a space around the * operator – Jeff Schaller Jan 1 '17 at 15:46
• ... and escape/quote it I think e.g. `expr "\$i" \* "\$j"` – steeldriver Jan 1 '17 at 16:54

Yes, you can use bash's built-in Arithmetic Expansion `\$(( ))` to do some simple maths.

For Multiplication:

``````echo \$(( 6 * 7 ))
``````

Result

``````42
``````

And your script would look like this:

``````#!/ in/bash

for i in 1 2 3 4 5 6 7 8 9

do

for j in 1 2 3 4 5 6 7 8 9
do
if [ \$j -le \$i ]
then
echo -ne "\$i"X"\$j"=\$((\$i * \$j)) "\t"
else
echo
break
fi
done
done
echo -ne "\n"
``````

Simplifying the solution a bit, by removing an unnecessary test:

``````#!/bin/bash

for (( i = 1; i < 10; ++i )); do
for (( j = 1; j <= i; ++j )); do
printf '%dx%d=%-2d  ' "\$i" "\$j" "\$(( i * j ))"
done
printf '\n'
done
``````