-2

This question already has an answer here:

I get

$ ./5_divisible_by_1_to_10.sh 
./5_divisible_by_1_to_10.sh: line 16: [: -eq: unary operator expected
 false
true

for:

divisible_by () {
  under_test=$1
  from=2
  to=4
  divisible=0
  for ((check=from; check<=to; check++)) {
    if [ $(($under_test % $check)) -ne 0 ]; then
      divisible=1
    fi  
  }
  return $divisible
}

divider=10
x= divisible_by "$divider"
if [ $x -eq 0 ]; then  # <--- Line 16
  echo "$x true"
else
  echo "$x false"
fi
divider=12
if divisible_by $divider; then
  echo "true"
else
  echo "false"
fi

The second call for 12 works ok but the first call using 10, where I am trying to display the result gives the error.

Adding quotes around $x, i.e "$x" gives a different error:

$ ./5_divisible_by_1_to_10.sh 
./5_divisible_by_1_to_10.sh: line 16: [: : integer expression expected
 false
true

marked as duplicate by Gilles, jimmij, Hauke Laging, Michael Homer, cuonglm Jan 5 '15 at 4:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • again - $x is empty. The syntax for test is [ num -op num ] and you feed it [ -op num ]. That won't work. – mikeserv Jan 5 '15 at 0:05
1

In

if [ $x -eq 0 ]

x is empty because the line

x= divisible_by "$divider"

is wrong: It calls divisible_by with the empty environment variable x but doesn't even try to set x in the shell environment. You need:

divisible_by "$divider"
x=$?

And you should always quote your variables.

Not the answer you're looking for? Browse other questions tagged or ask your own question.