Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script not working

Tags:

bash

I am writing the script to print multiplication table.

#!/bin/bash
a=1
while [ $a -le "10" ]
do

tmp=`expr $a * $1`
printf "%d x %d = %d\n" $1 $a $tmp
a=`expr $a + 1`

done

It gives syntactical error.

like image 275
Hitesh Menghani Avatar asked Aug 08 '26 10:08

Hitesh Menghani


1 Answers

Escape * as following

while [ $a -le "10" ]
do
    tmp=`expr $a \* $1`
    printf "%d x %2d = %3d\n" $1 $a $tmp
    a=`expr $a + 1`
done

Plz note \* in above code.
Here bash interprets * as wild character. So you need to escape it to literal star(i.e multiplication. If you dont want to escape * then you can use (( )) which performs arithematic operations.

while [ $a -le "10" ]
do
    ((tmp = $a * $1))
    printf "%d x %2d = %3d\n" $1 $a $tmp
    ((a++))
done
like image 72
Kaunteya Avatar answered Aug 11 '26 09:08

Kaunteya