简体   繁体   中英

Shell Script command not found error

Below my script for up to n prime numbers. When I run it, it always shows an error that command not found in line 12 and 18 both. What am I doing wrong?

clear    
echo"enter the number upto which you want prime numbers : "    
read n

for((i=1;i<=n;i++))    
do    
    flag=0 
    for((j=2;j<i;j++))
    do
        if [expr $i % $j-eq 0]    
        then
            flag=1
        fi
    done

    if [$flag-eq 0]
    then
        echo $i
    fi
done

As pointed out in comments, you must use spaces around [ and ] , as well as the comparison operators. Even more safe when using [ and ] is quoting your variables to avoid word splitting (not actually required in this specific case, though).

Additionally, you want to compare the output of expr to 0, so you have to use command substitution:

if [ $(expr "$i" % "$j") -eq 0 ]

and

if [ "$flag" -eq 0 ]

Since you're using Bash, you can use the (( )) compound command:

if (( i % j == 0 ))

and

if (( flag == 0 ))

No expr needed, no command substitution, no quoting required, no $ required, and the comparison operators have their "normal", expected meaning.

There are a number of syntax errors other than the brackets of if statement. Kindly go through the piece of code below. I have checked it running on my system.

#!/bin/sh
echo "enter the number upto which you want prime numbers : "
read n

for((i=1;i<=n;i++))
do
  flag=0
  for((j=2;j<i;j++))
  do
    if [ `expr $i % $j` -eq 0 ]
      then flag=1
    fi
  done

  if [ $flag -eq 0 ]
    then echo $i
  fi
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM