【问题标题】:How to print even numbers from a user supplied input [duplicate]如何从用户提供的输入中打印偶数 [重复]
【发布时间】:2017-11-24 22:26:47
【问题描述】:

我在这里有这段代码,它应该做什么:

用户输入最大数。并根据输入的数字,我想显示该数字之前的所有偶数。

#! /bin/bash
echo "What is your max number:"

read counter


for number in {0.."$counter"}

if [ (($number % 2 == 0)) ]
then
echo "$number"
fi

但它不起作用。而是当我从终端调用他的脚本时收到此错误:

[root@sunshine Desktop]# bash Tester
What is your max number:
9
Tester: line 9: syntax error near unexpected token `if'
Tester: line 9: `if [ (($number % 2 == 0)) ]'

【问题讨论】:

    标签: linux bash


    【解决方案1】:

    您忘记了for 循环的dodone 部分。 在任何情况下,您都不能使用 {a..b} 语法的变量, 很遗憾。 您需要改为编写为计数循环。 然后你可以增加2, 这消除了对偶数的检查:

    for ((number = 0; number < counter; number += 2)); do
        echo "$number"
    done
    

    最后,我建议将变量重命名为:

    • counter -> max
    • number -> counter

    把它们放在一起:

    #!/bin/bash
    
    echo "What is your max number:"    
    read max
    
    for ((counter = 0; counter < max; counter += 2)); do
        echo "$counter"
    done
    

    【讨论】:

    • 不能使用 {0..$var} 的原因是大括号扩展是在参数扩展之前完成的,因此在 Bash 处理它时它不是有效的扩展。您可以参考manual了解更多信息。
    【解决方案2】:

    更简单的方法:

    seq 0 2 $counter
    

    变量可以传递给大括号扩展,使用bash的另一个调用:

    bash -c 'printf "%i\n" {0..'$counter'..2}'
    

    eval:

    eval 'printf "%i\n" {0..'$counter'..2}'
    

    最后两种方法都不安全,除非确定$counter 是一个数字。

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 2015-12-06
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      相关资源
      最近更新 更多