Expected operando in for loop shell script

Asked

Viewed 75 times

0

I am creating a function in shell script that says if the number is prime or not, but I am getting a syntax error in for loop that the function has and I could not find how to fix.

   # ...
 9 ehPrimo() {
10     n=$0
11     numDivisores=1
12      
13     for (( i = 2; i < n/2; i++ ))
14     do
15         if [ n%2==0 ]
16         then
17             numDivisores++
18         fi
19     done
20     if [ numDivisores == 1 ]
21     then
22         return 1
23     else
24         return 0
25     fi
26 }
27 
28 echo $(ehPrimo 2)
   # ...

The mistake is: ./arquivo.sh: line 13: ((: ./arquivo.sh: syntax error: operand expected (error token is "./arquivo.sh")

1 answer

0


I’ve removed the syntax errors, but I think your logic is flawed...

#!/bin/bash

ehPrimo() {

  n=$1            # primeiro parametro e' $1, nao $0
  numDivisores=1

  for (( i = 2; i < n/2; i++ ))
  do
    ((x = n % 2))     # operacao aritmetica
    if [ $x -eq 0 ]   # comparacao numerica para numeros e' "-eq" e nao "=="
    then
      ((numDivisores++)) # operacao aritmetica
    fi
  done

  if [ $numDivisores -ne 1 ] # comparacao numerica
  then
    return 1
  else
    return 0
  fi
}

if ehPrimo $1; then
  echo "* primo"
else
  echo "* nao e' primo"
fi
  • I tidied up the logical part here but no more problems with syntax, thank you! I would like to understand what this is * in theecho "* primo", would be replaced by $1? Why here he only prints the asterisk even so I switched the line by echo "$1 primo".

  • echo "* prime" is just a message.... within quotation marks the "*" has no special meaning

Browser other questions tagged

You are not signed in. Login or sign up in order to post.