使用expr命令计算整数加法时遭遇non-integer argument错误的解决咨询
Hey there! Let's work through why your expr command is throwing that non-integer argument error—this is a super common gotcha with the expr tool, so I’ve got a few fixes to try:
Double-check variable assignment spacing
Make sure you didn’t add spaces around the=when setting your variables. For example,num1 = 20is wrong (it tries to run a command callednum1with arguments=and20), butnum1=20is correct. Your code looks like it’s doing this right, but it’s worth double-checking if you accidentally added spaces when typing.Ensure spaces around the
+operator inexpr
Theexprcommand is picky about whitespace around operators. If you wroteexpr $num1+$num2(no spaces around+), it’ll treat the whole string like a single non-integer argument. Your code usesexpr $num1 + $num2which is correct, but confirm there are actual spaces before and after the+in your terminal input—sometimes accidental typos happen here.Verify your variables hold pure integers
Runecho $num1andecho $num2to make sure they output just20and5with no extra spaces, newlines, or other characters. If, for example,num1got set to" 20"(with a leading space) somehow,exprwill reject it as a non-integer.Switch to Bash’s built-in arithmetic expansion (easier alternative)
If you want to avoidexpr’s quirks entirely, Bash has its own way to do arithmetic that’s more forgiving. Just use this syntax instead:num1=20 num2=5 echo $((num1 + num2))This will output
25without any ofexpr’s whitespace headaches.
Give these steps a try—chances are one of them will fix your error!
备注:内容来源于stack exchange,提问作者dhebbie Godspride

