You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Bash问候脚本出现‘Integer Expression Expected’报错的解决咨询

Fixing "integer expression expected" Error in Your Bash Greeting Script

Let's break down why you're getting that error and fix it step by step:

The Root Cause

When you run set $(date), Bash splits the full date output into positional parameters. By default, date outputs something like Wed Oct 11 06:19:20 UTC 2024—so $4 ends up being 06:19:20, a string with colons. The -lt operator in [ ... ] expects integer values for comparison, hence the "integer expression expected" error.

Also, your original script has a small syntax bug: the elif line is missing the then keyword, which would cause another error once you fix the integer issue.

Instead of splitting the entire date output, use date +%H to directly get the 24-hour format hour as a pure integer. This is cleaner and avoids string parsing headaches:

#!/bin/bash
# greetings
hour=$(date +%H)
if [ "$hour" -lt 12 ]; then
    echo "Good Morning"
elif [ "$hour" -lt 18 ]; then
    echo "Good Afternoon"
else
    echo "Good Evening"
fi
exit
  • date +%H outputs the hour as two digits (00-23), so hour holds a valid integer.
  • Added the missing then after elif to fix the syntax error.
  • Added #!/bin/bash at the top to explicitly specify the shell (good practice for portability).

Solution 2: Keep Using set but Parse the Hour from $4

If you want to stick with the set approach, you can extract the first two characters of $4 (the hour part) using Bash's string slicing:

#!/bin/bash
# greetings
set $(date)
hour=${4:0:2} # Grab first 2 characters of $4 (e.g., "06" from "06:19:20")
if [ "$hour" -lt 12 ]; then
    echo "Good Morning"
elif [ "$hour" -lt 18 ]; then
    echo "Good Afternoon"
else
    echo "Good Evening"
fi
exit

${4:0:2} tells Bash to take the substring of $4 starting at index 0, for a length of 2 characters—turning the time string into a valid integer for comparison.

内容的提问来源于stack exchange,提问作者Yousif Dafalla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:58:32