FrostL FrostL - 3 months ago 11
Bash Question

Expr and count in shell

I learn a shell code from a video,and there is a code:

#!/bin/sh

i=1

while true
do
echo $i
i='expr $i + 1'
done


The code above gives me output is:

1
expr $i + 1
expr $i + 1
expr $i + 1
......


But in the video the output are consistent numbers,why the same code shows different results?

Answer

As aready mentioned in a comment, you have the wrong quotes; the video will have had backticks (`, ASCII 96), not single quotes (', ASCII 39).

Additionally, anything which uses this obsolescent syntax for command substitution or expr is at least 20 years behind, and should be avoided in favor of modern POSIX constructs.

#!/bin/sh

i=1

while true
do
    echo "$i"  # Note proper quoting
    i=$((i+1))
done

In Bash, you could use brace expansion or a C-style for loop, but these are not portable to modern sh.

If you need your code to be portable to pre-POSIX systems, my recommendation would still be to learn the modern constructs first, especially for simple code like this (where in a production system you would probably want to use Awk or Perl for a loop like this anyway).