Shell Scripts整数表达式预期

时间:2018-04-08 13:29:11

标签: linux ubuntu-16.04

我正在尝试在bash中运行以下脚本

#greetings
set `date`
if [ "$4" -lt 12 ]
then 
  echo "Good Morning"
elif [ "$4" -lt 18 ]
  echo "Good Afternoon"
else
  echo "Good evening"
fi
exit

我一直在纠错./greetings:第3行:[:06:19:20:期望整数表达式

我该怎么办?

2 个答案:

答案 0 :(得分:1)

如果您在脚本的最开头尝试echo $4,您将获得以下格式的结果:

%H:%M:%S

例如,

$ date
16:41:22

此结果无法解析为整数。

一种解决方案是仅设置小时而不是整个日期,并使用$1(而不是$4):

# greetings
set `date +%H`
if [ "$1" -lt 12 ]
then
  echo "Good Morning"
elif [ "$1" -lt 18 ]
then
  echo "Good Afternoon"
else
  echo "Good evening"
fi
exit

此外,请注意您在then之后遗漏了elif个关键字。

答案 1 :(得分:0)

TIME=`date +%H:%M:%S | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }'`

if [ "$TIME" -lt 43200 ]; then 
  echo "Good Morning"
elif [ "$TIME" -lt 64800 ]; then
  echo "Good Afternoon"
else
  echo "Good evening"
fi
exit

所有时间都转换为秒