-4
#!/bin/bash
var=1
if [[ $var -eq 0 ]]
then
    echo "No students"
elif [[ $var -eq 1 ]]
then
    echo "1 student"
elif [[ $var -eq 2]]
then
    echo "2 students"
elif [[ $var -eq 3 ]]
then 
    echo "3 students"
elif [[ $var -eq 4 ]]
then
    echo "4 students"
else
    echo "A lot of students"
fi

I've written this bash script . But it throws this error:

Failed test #1. Runtime error:
main.sh: line 11: syntax error in conditional expression
main.sh: line 12: syntax error near `then'
main.sh: line 12: `then'
Zanna
  • 70,465
Kanat
  • 399
  • 4
  • 6
  • 17

2 Answers2

9

The problem is elif [[ $var -eq 2]], it should be: elif [[ $var -eq 2 ]].

Spacing matters.

The thing is when it see a [[ it looks for closing ]] and it can't find it instead it see 2]] which doesn't have any meaning.

Ravexina
  • 55,668
  • 25
  • 164
  • 183
  • Thanks dude , I have one more question ! how to get asnwer like that 0 --> No students 1 --> 1 student 2 --> 2 students 3 --> 3 students 4 --> 4 students 5 и больше --> A lot of students – Kanat Jun 28 '17 at 14:19
  • it should work: [[ $var -ge 5 ]] – Ravexina Jun 28 '17 at 14:23
5

case would be a good choice here to reduce the code.

case $var in
  0) echo "No students" ;;
  1|2|3|4) echo "$var students" ;;
  *) echo "A lot of students" ;;
esac
glenn jackman
  • 17,900
  • 1
    While I agree that this would be better, the question asks about if statement specifically, which you didn't address. Just saying. – Sergiy Kolodyazhnyy Jun 29 '17 at 04:55
  • I have to disagree with @Sergiy Kolodyazhnyy here ... The question was "What is the problem in my bash script?" and depending on the level of view one could say in this case the usage of case fixes the if-else problem even better – derHugo Jun 29 '17 at 05:29
  • 1
    @derHugo there's a bit of difference between replacing code with alternative and fixing code. Like I said in my previous comment, the answer may provide better solution, but it doesn't address the core issue – Sergiy Kolodyazhnyy Jun 29 '17 at 05:47