0

I wrote small bash script

for (( j=10;j<20; j++ ))
    do
    ./b5 $j $[ $1 * 3 ]
    done

Which should execute program b5 and send two parameters, $j and $1 multiplied by 3.

When I try to run it, i get:

 * 3 : syntax error: operand expected (error token is "* 3 ")

How should one do it?

Yurkee
  • 795
  • 2
  • 9
  • 23

3 Answers3

1

You should do expr $1 \* 3 to multiply variable by a digit.

agilob
  • 6,082
  • 3
  • 33
  • 49
  • `$((...))` almost wholly subsumes the need for `expr` in any POSIX shell. The only thing you really need `expr` for is regular expression matching for shells that don't already provide their own. – chepner Sep 06 '16 at 11:47
1

You have to use $((..)) for doing arithmetic expression.

Instead,

./b5 $j $[ $1 * 3 ]

to

./b5 $j $(($1 * 3))
sat
  • 14,589
  • 7
  • 46
  • 65
  • You don't *have* to; `$[ ... ]` is an obsolete but still valid form of arithmetic expansion. The bigger problem is that `$1` doesn't appear to be set. – chepner Sep 06 '16 at 11:47
  • @chepner, Ohh..ok. I got it..thanks. I just found the difference in this link : http://stackoverflow.com/questions/2415724/bash-arithmetic-expression-vs-arithmetic-expression – sat Sep 06 '16 at 11:54
  • I do wonder when it will be removed from `bash`, though; it still works in the upcoming 4.4 release. – chepner Sep 06 '16 at 12:14
1

To be honest, both options work:

  • $(( $1 * 3 ))
  • $[ $1 * 3]

but he problem was $1 was not initialized. My mistake.

Yurkee
  • 795
  • 2
  • 9
  • 23