mercredi 4 juillet 2018

Bash Script for loop with nested if statement

I have a script like this:

 #!/bin/bash

 x=${1:-20}

 for ((i=1;i<=x;i++))
 {
      if ((i%3==0))
      {
            echo 'Fizz'
      }
    echo $i
 }

I get an error color on the last brace in VIM and when I try to run the script I get a "syntax error near unexpected token" for that same brace. Without the nested if statement, this will print 1 through 20 on a new line for each number, which is the expected outcome. If the number is divisible by 3, it should print Fizz instead of that number. I'm not as worried about how to implement the replacement, that should be easy to figure out, but what I don't understand is why I cannot use a brace to close the for loop. If I take out the brace, I get an error that says end of file expected. So what is the proper syntax for ending a for loop with a nested if statement? I've looked around online and here on stack but haven't found a similar format to what I am trying to do. I don't like the

 for f in * 

format as it is not as easy to read for someone coming from a different coding language and I like to keep my code looking very similar across different languages (I use comments too, but just the same, I try to keep things as similar as possible which is why I used (( )) with the for loop.)

If I comment out the if statement and leave everything else intact, the error disappears and it will print

 1
 Fizz
 2
 Fizz

 etc.

Any insight into this would be greatly appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire