There are a few technical problems with your code, and also (if I understand what you are trying to do correctly) some logical errors in the design.
I'll share a few comments about how I looked at this. First thing to note is that the code you show is inconsistently indented, which means it is hard to see the logical structure of the code by simply looking at it. I loaded this into my usual editor (VSCode) which has a handy "Format Document" feature (many other code editors have similar auto-format features), and that produced the following:
#!/bin/sh
i=2
while [ $i -le 100]; do
c=0
j=1
while [ $j -lt $i ]; do
if [ $(($i % $j)) -eq 0 ]; then
c=$(($c + 1))
fi
j=$(($j + 1))
if [ $c -eq 0 ]; then
echo i
fi
done
i=$(($i + 1))
done
Note how this properly shows the nesting of statements within the inner while loop, in contrast to the original code. Even if you don't have access to a fancy editor, it is worthwhile spending the time to ensure that your code is manually indented correctly. It will save you a lot of time later in understanding and debugging the code.
Note also that the echo i
line towards the end of the code should be echo $i
if you want to print the value of the i
variable.
When I try to run this code, it actually gives me an error telling me there's a missing ]
in line 4. You need a space after the 100
here (as also pointed out by Stéphane Veyret):
while [ $i -le 100 ]; do
Next up, I added extra echo
lines at various points in the code just to debug it. For example, the first thing I tried was to add the following line just before the final done
line (the last line of the code)
echo "i=" $i
When I run the code I see this message printed multiple times, which tells me that the loop is running and that i is getting incremented from 2 to 100 as expected. I then added further echo lines at places within the while loop to check the values of other variables too.
These investigations highlighted a problem in your logic in the line
if [ $(($i % $j)) -eq 0 ]; then
The variable j
is set to 1 at the start of each pass of the outer while loop. Any number modulus 1 is equal to zero, so this test will always be true when j
is 1. This means that c
will always be incremented the first time this code is encountered in each pass of the outer while loop (c=$(($c + 1))
). And that means that the following test (if [ $c -eq 0 ]; then
) will never be true.
I hope that gives you some ideas of what the problems are and how to go about further testing and debugging the code to make it do what you want.