如何用Bash脚本实现整数求和?现有代码问题排查
Let's break down the issues in your script and fix them step by step:
Key Problems in the Original Code
- Case sensitivity: Bash commands and variables are case-sensitive. Your first line uses
Read(capital R) which isn't a valid built-in command, and you initializedSum=0but later referencedsum(lowercase)—these are two separate variables, so your initial 0 value was never being used. - String concatenation instead of arithmetic: The line
sum=sum+numberjust combines text strings ("sum", "+", and the input number) instead of performing actual integer addition. Bash requires explicit syntax to do math operations.
Corrected Script
#!/bin/bash read N sum=0 for ((i=1; i<=N; i++)) do read number sum=$((sum + number)) done echo $sum
Explanation of Fixes
- Fixed input command: Changed
Readto lowercasereadso Bash recognizes it as the standard input-reading command. - Consistent variable naming: Used lowercase
sumthroughout to ensure the initial 0 value is properly updated with each iteration. - Arithmetic expansion: Replaced
sum=sum+numberwithsum=$((sum + number)). The$((...))syntax tells Bash to evaluate the expression inside as a numerical calculation, not string concatenation.
Alternative Concise Version
You can also use the let built-in for shorter arithmetic assignment:
#!/bin/bash read N sum=0 for ((i=1; i<=N; i++)) do read number let sum+=number done echo $sum
Both versions will correctly sum your input integers. For example, if you enter 3 when prompted for N, then input 1, 2, 3, the script will output 6.
内容的提问来源于stack exchange,提问作者Kate




