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 Answers 2
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
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.
lang-bash
expr "$i" \* "$j"