Shell脚本if语句失效:无法根据系统时间输出对应问候语
问题:Bash时间问候脚本逻辑错误,下午4点触发else分支
用户提供的Bash脚本如下:
#!/bin/bash clear echo "Wishing according to Time of the PC" h=$(date '+%H') #This line works, I've Checked. if test $h -gt 6 -a $h -lt 12 then echo "Good Morning" elif test $h -gt 12 -a $h -lt 16 then echo "Good Afternoon" elif test $h -gt 16 -a $h -lt 20 then echo "Good Evening" else echo "Good Night" fi
当前系统时间为下午4点(24小时制的16点),但脚本始终跳转到else分支输出Good Night,嵌套if也无效,系统为Linux 7.9。
解决方案
问题根源
脚本的条件区间存在边界值遗漏:
下午4点对应24小时制的16,但第二个elif仅匹配13-15点($h -gt 12 -a $h -lt 16),第三个elif仅匹配17-19点($h -gt 16 -a $h -lt 20),16这个值没有被任何条件覆盖,因此直接进入else分支。
修改后的脚本(两种可选写法)
写法1:调整条件包含边界值,保留test命令
#!/bin/bash clear echo "Wishing according to Time of the PC" h=$(date '+%H') if test $h -gt 6 -a $h -lt 12 then echo "Good Morning" elif test $h -ge 12 -a $h -le 16 # 修改为包含12和16点 then echo "Good Afternoon" elif test $h -gt 16 -a $h -lt 20 then echo "Good Evening" else echo "Good Night" fi
写法2:使用Bash原生[[ ]]语法(推荐,可读性更强)
#!/bin/bash clear echo "Wishing according to Time of the PC" h=$(date '+%H') if [[ $h -gt 6 && $h -lt 12 ]] then echo "Good Morning" elif [[ $h -ge 12 && $h -le 16 ]] then echo "Good Afternoon" elif [[ $h -gt 16 && $h -lt 20 ]] then echo "Good Evening" else echo "Good Night" fi
额外说明
如果希望下午4点(16点)属于Good Evening,只需将第三个elif的条件改为[[ $h -ge 16 && $h -lt 20 ]]即可。[[ ]]是Bash的扩展语法,比传统test命令更安全,支持逻辑运算符&&/||,能避免很多字符串解析的坑。
内容的提问来源于stack exchange,提问作者Dilip
相关产品推荐
相关产品推荐

