Bash script error: [i: command not found

2019-02-26 03:36发布

This program is suppose to accept a number from the user and print that many prime numbers. For some reason the program doesn't work. I am new to bash scripting and this is my first program. To my eyes everything seems to be correct. Please tell me where I went wrong.

echo Enter num
read n
i=2
j=2

for(( i=2; i <= n; i++ ))
do

for(( j=2; j < i-1; j++ ))
do

if [i % j == 0];
then
break
fi


if [i == j];
then
echo "  $i"
fi
done
done

This is the output I get

Enter num
20
prime.sh: line 12: [i: command not found
prime.sh: line 18: [i: command not found
prime.sh: line 12: [i: command not found
prime.sh: line 18: [i: command not found
 .
 .
 .

After making the suggested changes

read -p "Enter a  number : " n
i=2
j=2
for(( i=2; i <= n; i++ ))
do
    for(( j=2; j <= i-1; j++ ))
    do
        if [ $(( i % j )) == 0 ]
        then
            break
        fi
        if [ i == j ]
        then
            echo "  $i"
        fi
    done
done

I was able to run the program but it didn't produce any result

http://i.stack.imgur.com/Fd1se.png

标签: bash shell
4条回答
▲ chillily
2楼-- · 2019-02-26 04:02
#!/bin/bash
#
# primes
#
read -p "Enter a  number: " n
i=2

for (( i=2; i <= n; i++ ))
do
    for (( j=2; j*j < i; j++ ))
    do
        if ((i % j == 0))
        then
            echo "no prime, $i divider: "$j
            break
        fi
    done
done

updated, after realizing (thanks Will Ness), that all primes up to INPUT are searched.

i needs to run to √(n) only.

查看更多
三岁会撩人
3楼-- · 2019-02-26 04:18

You need to place a space after the [ because [ is an application.

And you can't make calculations between the brackets. You will need to tell bash it needs to calculate the values. So you would need to change line 11 to if (( i % j == 0 )).

查看更多
叛逆
4楼-- · 2019-02-26 04:22

if [i % j == 0]; Should be if [ i % j == 0 ];

Same for the one on line 18

查看更多
走好不送
5楼-- · 2019-02-26 04:24

Like the others have said, the [ program needs a space before its parameters, like all programs need a space before their args. This is one reason why I prefer the test builtin to [ with its kludgy syntax requiring a useless ] as the last arg just to make it look pretty and sane.

if test $((i % j)) = 0; then
   break
fi
查看更多
登录 后发表回答