我在 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

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

I am getting expr syntax errors in bash shell for a simple program

bashexpr

提问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 sto zero, rather it tries to run the command swith the two arguments, =and 0.

例如,s = 0(带有空格)不会将变量s设置为零,而是尝试s使用两个参数=0.

However, it's not really necessaryto call the external expr1to do mathematical manipulation and capture the output to a variable. That's because bashitself can do this well enough withoutresorting to output capture (see ARITHMETIC EVALUATIONin the bashman page):

但是,实际上并没有必要调用外部expr1来进行数学运算并将输出捕获到变量中。这是因为bash本身就可以做到这一点不够好,而不诉诸输出捕获(见ARITHMETIC EVALUATIONbash手册页):

#!/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 :-)

但是,老实说,我想我更喜欢可读的解决方案:-)