运行Bash问候脚本出现‘Integer Expression Expected’报错的解决咨询
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.
Solution 1: Simplify with Direct Hour Extraction (Recommended)
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 +%Houtputs the hour as two digits (00-23), sohourholds a valid integer.- Added the missing
thenafterelifto fix the syntax error. - Added
#!/bin/bashat 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

