0

I wanted to write a script to print 10 number using while loop. I tried the following code

#!/bin/sh
i=0 

while [ $i -lt 10 ]
do
    echo "$i"
    i='expr $i + 1'
done

but I am getting the following error

sh: $i: unknown operand

can anyone explain me why its raising error?

Danish Mahmood
  • 307
  • 2
  • 7
  • 3
    You want backticks, `\``, not single quotes, `'`, around the righthand side of your `i=` assignment. (Or even better, `$(...)`, the modern alternative to backticks.) – Benjamin W. Mar 06 '20 at 00:55
  • 2
    It's not *modern* to use `expr` at all. POSIX-standardized math syntax is `i=$(( i + 1 ))`, whereas the bash-extended approach is simply `(( ++i ))` – Charles Duffy Mar 06 '20 at 01:01
  • 2
    See https://wiki.bash-hackers.org/scripting/obsolete re: `expr`, `let`, `$[ ... ]`, and various other artifacts of antiquity. (well -- `expr` isn't covered there, but that's because it isn't even part of bash *at all*; when you use `expr` in bash, it runs a completely separate program like `/usr/bin/expr`, not part of your shell) – Charles Duffy Mar 06 '20 at 01:03

0 Answers0