BASH脚本出现[2: command not found]错误,请求排查解决
解决Bash脚本中的
[2: command not found]错误及逻辑问题 错误原因分析
你遇到的[2: command not found]是典型的Bash语法问题——[是test命令的简写,作为内置命令,它必须和后面的参数保留空格。你的第26行代码里[$y -lt $MIN ]和[$y -eq 0],[直接跟$y拼接,当输入y=2时,Bash会把[$y]解析成[2这个不存在的命令,自然报错。
其他隐藏问题
除了这个语法错误,脚本还有两个需要修正的点:
- for循环里的运算符列表
{"+","-","*","/",}多了一个末尾逗号,会生成空运算符,最终输出多余的0(就是你看到的最后一行无效输出)。 - bc的
/是浮点数除法,不符合题目要求的「只输出整数部分」,比如输入5和2时,bc会输出2.5,而题目需要的是截断后的整数2。
修正后的完整脚本
#!/bin/bash # Given two integers X and Y. find their sum, difference, product, and quotient # Constraints # -100 <= X,Y <= 100 # Y != 0 # Output format # Four lines containing the sum (X+Y), difference (X-Y), product (X x Y), and the quotient (X // Y) respectively. # (While computing the quotient print only the integer part) # Read data echo "Please input for x and y!" read x read y declare -i MIN=-100 declare -i MAX=100 # Checks if the valued read is in the constraints if [ $x -gt $MAX ] || [ $x -lt $MIN ]; then echo "Error!" exit 1; elif [ $y -gt $MAX ] || [ $y -lt $MIN ] || [ $y -eq 0 ]; then echo "Error" exit 1; else # 用Bash整数运算直接计算,自动截断取整,符合题目要求 echo $((x + y)) echo $((x - y)) echo $((x * y)) echo $((x / y)) # 若坚持用bc,需添加scale=0强制取整: # for operator in {"+","-","*","/"}; do echo "scale=0; $x $operator $y" | bc; done fi
关键修改点说明
- 条件判断空格修复:把所有
[$y改成[ $y,0];改成0 ];,确保[和]作为命令分隔符被正确识别。 - 运算符列表修正:去掉末尾逗号,避免生成空运算符导致无效输出。
- 整数商处理:改用Bash内置的
$((...))整数运算,自动截断取整,完全匹配题目要求;若使用bc,需在表达式前添加scale=0;强制取整。
测试验证
输入1和2时,修正后的脚本会输出:
3 -1 2 0
无错误提示,结果完全符合要求。
内容的提问来源于stack exchange,提问作者Rifky Satyana
相关产品推荐
相关产品推荐

