我在 bash shell 中遇到一个简单程序的 expr 语法错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30497074/
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
I am getting expr syntax errors in bash shell for a simple program
提问by Robo Smith
#!/bin/bash
clear
echo "Enter a number"
read a
s = 0
while [ $a -gt 0 ]
do
r = ` expr $a % 10 `
s = ` expr $s + $r `
a = ` expr $a / 10 `
done
echo "sum of digits is = $s"
This is my code guys . I am getting a bunch of expr syntax errors. I am using the bash shell. Thanks!
这是我的代码家伙。我收到一堆 expr 语法错误。我正在使用 bash shell。谢谢!
回答by paxdiablo
Your error is caused by the spaces surrounding the =
in the assignments, the following replacements should work (I prefer $()
to using backticks since they're much easier to nest):
您的错误是由=
分配中的空格引起的,以下替换应该有效(我更喜欢$()
使用反引号,因为它们更容易嵌套):
s=0
r=$(expr $a % 10)
s=$(expr $s + $r)
a=$(expr $a / 10)
For example, s = 0
(with the spaces) does not set the variable s
to zero, rather it tries to run the command s
with the two arguments, =
and 0
.
例如,s = 0
(带有空格)不会将变量s
设置为零,而是尝试s
使用两个参数=
和0
.
However, it's not really necessaryto call the external expr
1to do mathematical manipulation and capture the output to a variable. That's because bash
itself can do this well enough withoutresorting to output capture (see ARITHMETIC EVALUATION
in the bash
man page):
但是,实际上并没有必要调用外部expr
1来进行数学运算并将输出捕获到变量中。这是因为bash
本身就可以做到这一点不够好,而不诉诸输出捕获(见ARITHMETIC EVALUATION
的bash
手册页):
#!/bin/bash
clear
read -p "Enter a number: " number
((sum = 0))
while [[ $number -gt 0 ]]; do
((sum += number % 10))
((number /= 10))
done
echo "Sum of digits is $sum"
You'll notice I've made some other minor changes which I believe enhances the readability, but you could revert back to the your original code if you wish and just use the ((expression))
method rather than expr
.
你会注意到我做了一些其他的小改动,我相信这些改动提高了可读性,但如果你愿意,你可以恢复到原始代码,只需使用((expression))
方法而不是expr
.
1If you don't mindcalling external executables, there's no need for a loop in bash
, you could instead use sneakier methods:
1如果您不介意调用外部可执行文件,则不需要在 中循环bash
,您可以使用更隐蔽的方法:
#!/bin/bash
clear
read -p "Enter a number: " number
echo "Sum of digits is $(grep -o . <<<$number | paste -sd+ | bc)"
But, to be brutally honest, I think I prefer the readable solution :-)
但是,老实说,我想我更喜欢可读的解决方案:-)