bash 在bash脚本中打印奇数给出错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46265305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:27:54  来源:igfitidea点击:

Printing odd numbers in bash script giving error

bashshell

提问by Neha Sharma

Please tell why printing odd numbers in bash script with the following code gives the error:

请说明为什么使用以下代码在 bash 脚本中打印奇数会出现错误:

line 3: {1 % 2 : syntax error: operand expected (error token is "{1 % 2 ")

第 3 行:{1 % 2 :语法错误:预期操作数(错误标记为“{1 % 2”)

for i in {1 to 99}
do
rem=$(( $i % 2 ))
if [$rem -neq 0];
then
echo $i
fi
done

回答by DevDio

This is working example:

这是工作示例:

for i in {1..99}
do
        rem=$(($i % 2))
        if [ "$rem" -ne "0" ]; then
                echo $i
        fi
done
  1. used forloop have a typo in minimum and maximum number, should be {1..99}instead of {1 to 99}
  2. brackets of the ifstatement needs to be separated with whitespacecharacter on the leftand on the rightside
  3. Comparision is done with neinstead of neq, see this reference.
  1. 使用的for循环在最小和最大数量上有一个错字,应该{1..99}代替{1 to 99}
  2. if语句的括号需要用和边上的whitespace字符分隔leftright
  3. 比较是使用ne而不是完成的neq请参阅此参考资料

As already pointed out, you can use this shell checkerif you need some clarification of the error you get.

正如已经指出的那样,如果您需要澄清您得到的错误,您可以使用这个 shell 检查器

回答by Akshay Hegde

To print odd numbers between 1 to 99

打印 1 到 99 之间的奇数

seq 1 99 | sed -n 'p;n'

With GNU seq, credit to gniourf-gniourf

使用 GNU seq,归功于gniourf-gniourf

seq 1 2 99

Example

例子

$ seq 1 10 | sed -n 'p;n'
1
3
5
7
9

if you reverse it will print even

如果你反转它甚至会打印

$ seq 1 10 | sed -n 'n;p'
2
4
6
8
10

回答by FedFranzoni

Not really sure why nobody included it, but this works for me and is simpler than the other 'for' solutions:

不确定为什么没有人包含它,但这对我有用并且比其他“for”解决方案更简单:

for (( i = 1; i < 10; i=i+2 )); do echo $i ; done

回答by Cyrus

Replace {1 to 99}by {1..99}.

替换{1 to 99}{1..99}

回答by Jigar

for (( i=1; i<=100; i++ ))
do
    ((b = $i % 2))
  if [ $b -ne 0 ] 
    then
    echo $i
fi
done