This question already has answers here:
Bash error: Integer expression expected
(1 answer)
Closed last year.
I am a beginner at programming in Unix enviroment and I am facing some difficulties at start. I am using PUTTY on Windows.
Here is my script and the code but when I run it, it tells me that
integer expression expected
#!/bin/bash
hour='date|cut-c12-13'
if [ $hour -ge 0 -a $hour -lt 12 ]; then
echo "good morn"
elif [ $hour -lt 18 ]; then
echo "good afternoon"
else
echo "good night"
fi
It seems that it doesn't work correctly with the pipeline or something; it doesn't translate the 'date' to the original date but takes it as a word, I think.
Your code shows regular quotes '…'
and not back-ticks `…`
. Use
hour=$(date | cut -c12-13)
The spacing matters between cut
and -c12-13
. In general, using $(…)
is better than using back-ticks (see Pipe standard input and command line arguments in Bash for a discussion of why). Also, learn How to debug a Bash script, which means bash -x script.sh
here.
With the code as written, the value in $hour
is the string date|cut-c12-13
(not the output from the command) which is not an integer expression, hence the error message. Also, you most likely don't have a command called cut-c12-13
, which is why the spacing matters there.
As the comments to the question show, there are multiple other issues that should also be addressed, from generating the information you want directly from the date
command to using double quotes around variable references, not using deprecated operators -a
and -o
with [
, and there are those who'd argue that you should use [[ … ]]
in preference to [ … ]
, or the Bash-specific (( … ))
, etc.