Linux Bash脚本浮点输入报command not found错误求助
Bash脚本浮点工时输入报错问题解析
问题描述
我是一名学生,需完成学校实验作业。教授课堂编写的Bash薪资计算脚本,薪资结果正确,但输入浮点型工时(如30.20)时,会出现command not found错误。脚本代码及运行输出如下:
脚本代码
# MUST use a loop # MUST prompt user for input data # MUST use ecoh for calculation # Program that computes a payroll for a small company # 11.17.2022 # Johnathon Masias # ITSC 1307 FALL # Scripting Lab 8 # Variable declaration rate=0 hours=0 gross=0 counter=0 # Using a loop to collect data while [[ $counter -lt 3 ]] do echo "Please enter employee name" read name echo "Please enter hours worked" read hours echo "Please enter hourly rate" read rate # Compute gross pay using IF statement for overtime if [[ `"$hours"` -le 40 ]] then gross=`echo "scale=2; $hours * $rate" | bc` else gross=`echo "scale=2; (40 * $rate) + ($hours - 40)*($rate*1.5)" | bc` fi echo "$name worked $hours at a rate of $rate making a gross pay of $gross" read dummy counter=`expr $counter + 1` done
运行输出
Please enter employee name a Please enter hours worked 30.20 Please enter hourly rate 10.25 script08: line 30: 30.20: command not found a worked 30.20 at a rate of 10.25 making a gross pay of 309.55
注:教授未教授shebang的使用,我们不使用shebang。
错误原因分析
报错的核心在第30行的if [[ "$hours" -le 40 ]]语句:
- 此处的
`"$hours"`使用了反引号,Bash会将反引号内的内容当作命令执行,而非直接作为数值参与比较。当输入的hours是浮点数(如30.20)时,系统会尝试运行名为30.20的命令,显然不存在该命令,因此抛出command not found错误。 - 另外,Bash原生的
[[ ]]结构中,-le这类比较运算符仅支持整数比较,即便去掉反引号,直接用[[ $hours -le 40 ]]比较浮点数也会触发错误。
修复方案
要正确处理浮点数比较,需借助bc工具完成数值判断,修改if语句部分即可:
# 替换原有的if判断语句 if (( $(echo "$hours <= 40" | bc -l) )) then gross=$(echo "scale=2; $hours * $rate" | bc) else gross=$(echo "scale=2; (40 * $rate) + ($hours - 40)*($rate*1.5)" | bc) fi
修复说明
- 使用
echo "$hours <= 40" | bc -l让bc工具执行浮点数比较,返回1表示条件成立,0表示不成立。 (( ))结构可直接判断bc返回的整数结果,规避Bash原生的整数限制。- 将旧的反引号替换为
$(),这是Bash中更推荐的命令替换写法,可读性更强。
验证结果
修改后输入浮点工时(如30.20),脚本将正常执行,不再出现command not found错误,薪资计算结果依然准确。
内容的提问来源于stack exchange,提问作者newguy
相关产品推荐
相关产品推荐

