1

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?

asked Jan 1, 2017 at 15:11
2
  • 2
    Or put a space around the * operator Commented Jan 1, 2017 at 15:46
  • 1
    ... and escape/quote it I think e.g. expr "$i" \* "$j" Commented Jan 1, 2017 at 16:54

2 Answers 2

0

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"
answered Jan 1, 2017 at 15:18
0

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
answered Jan 4, 2017 at 19:48

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.