带有嵌套if语句的Bash脚本for循环

时间:2018-07-04 17:11:34

标签: bash for-loop if-statement

我有一个像这样的脚本:

 #!/bin/bash

 x=${1:-20}

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

我在VIM中的最后一个花括号上出现错误颜色,并且当我尝试运行脚本时,对于同一花括号,我收到“意外令牌附近的语法错误”。如果没有嵌套的if语句,这将在每个数字的新行上打印1到20,这是预期的结果。如果该数字可被3整除,则应打印Fizz而不是该数字。我不担心如何实现替换,应该很容易弄清楚,但是我不明白的是为什么我不能使用花括号来关闭for循环。如果取出括号,则会收到错误消息,提示文件预期结束。那么用嵌套的if语句结束for循环的正确语法是什么?我已经在网上四处查看,并且在此处,但是没有找到与我尝试的格式相似的格式。我不喜欢

 for f in * 

格式,因为来自其他编码语言的人阅读起来不那么容易,而且我希望保持我的代码在不同语言之间看起来非常相似(我也使用注释,但同样,我尝试将内容保留为尽可能类似,这就是为什么我将(())与for循环一起使用。)

如果我注释掉if语句并保留其他所有内容,错误将消失并且将打印

 1
 Fizz
 2
 Fizz

 etc.

任何对此的见解将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

感谢@Cyrus,这就是我能够找出的原因:

x=${1:-20}
for ((i=1;i<=x;i++))
do
  if ((i%3==0))
  then
    echo 'Fizz'
  else
    echo $i
  fi
done

在很多方面,bash比大多数其他语言都更简单,但是当您习惯于“高级”语言时,使用bash会变得更加困难。

答案 1 :(得分:0)

因此,为了帮助其他像我一样的人,并开始使用bash进行编码,这是我编写的完整程序,并附有注释说明为什么我以这种方式进行编码。如果我的说明或格式样式有误,请指出。谢谢!这样写很有趣,叫我疯了。

# This will literally just print the string inside the single quotes on the screen
echo 'Try running this again but with something like this: fizzbuzz 25 pot kettle black'

    # The $0 is the first index, in other words the file name of the executable, 
    # this will set the default value of x to 20 but will allow the user to input 
    # something else if they want.
    x=${1:-20}

    # This is the same but with string variables
    f=${2:-FizzBuzz}
    g=${3:-Fizz}
    b=${4:-Buzz}

        # We start the index variable at 1 because it's based on the input, 
        # otherwise it would echo 0 thru 19
        for ((i=1;i<=x;1++))

               do
                   # I recommend using (( )) for if statement arithmetic operations
                   # since the syntax is similar to other programming languages
                   if ((i%3==0 && i%5==0)); then echo $f

                   # you need to use a semicolon to separate if and then if they are 
                   # on the same line, otherwise you can just go to the next line for
                   # your then statement
                   else if ((i%3==0)); then echo $g

                   else if ((i%5==0)); then echo $b

                   else echo $1

                   # You need fi in order to finish an if then statement
                   fi fi fi
              done