Linux 算术表达式:期待 EOF:“008 +1”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10515407/
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
arithmetic expression: expecting EOF: "008 +1"
提问by craphunter
My script ./make_shift_ln_o_dummy.sh:
我的脚本 ./make_shift_ln_o_dummy.sh:
for i in `seq -w 0 272`
do
y=0
x=1
echo $i
y=$(($i +$x))
echo $y
done
My output with error message: arithmetic expression: expecting EOF: "008 +1"
我的错误信息输出:算术表达式:期待 EOF:“008 +1”
000
1
001
2
002
3
003
4
004
5
005
6
006
7
007
8
008
./make_shift_ln_o_dummy.sh: 25: arithmetic expression: expecting EOF: "008 +1"
Why does it happen? What do I do wrong? How should I change it to the output of 272?
为什么会发生?我做错了什么?我应该如何将其更改为 272 的输出?
回答by anubhava
No need to use seq
here. You can use bash arithmetic features like this:
seq
这里不需要使用。您可以像这样使用 bash 算术功能:
for ((i=0; i<272; i++))
do
y=0
x=1
printf "%03d\n" $i
y=$(($i + $x))
printf "%03d\n" $y
done
回答by msw
Why does it happen?
为什么会发生?
The bash expression evaluator sees the leading 0
and assumes that an octal constant is going to follow but 8
is not a valid octal digit.
bash 表达式计算器看到前导0
并假设8
后面跟着一个八进制常量,但不是一个有效的八进制数字。
Version 4.2 of bash
gives a more helpful diagnostic:
的 4.2 版bash
提供了更有用的诊断:
$ echo $((007 + 1))
8
$ echo $((008 + 1))
bash: 008: value too great for base (error token is "008")
The answer from anubhavaabove gave the "how to fix" which is why I upvoted it.
上面来自 anubhava的答案给出了“如何修复”,这就是我赞成它的原因。
回答by glenn Hymanman
008 is an octal number. You can specify you want to use a base-10 number in your arithmetic expression:
008 是八进制数。您可以指定要在算术表达式中使用以 10 为基数的数字:
y=$((10#$i +$x))
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic