Shafiq Mustapa
Shafiq Mustapa

Reputation: 433

Bash Script error: [: missing ]

#!/bin/bash
if [ `date +%u` -lt 6 && `date +%H` == '19' ] ; then
   echo 'Sorry, you cannot run this program today.'
else
   echo 'yes, you can run today'
fi

The script above is to run a program on weekdays and every 7PM. I have check the spaces and it still return error : date.sh: 2: [: missing ]

Upvotes: 3

Views: 16056

Answers (2)

Cairnarvon
Cairnarvon

Reputation: 27782

There are two problems with your code.

The first is a simple typo: date %H should be date +%H.

The second is the cause of the error you're seeing: && isn't the right operator to use. It separates commands, whereas your if condition should really be a single one; bash looks for ] at the end of [ `date +%u` -lt 6, doesn't find it, and errors out. You want to use -a instead.

Upvotes: 5

hek2mgl
hek2mgl

Reputation: 158020

Change it to:

#!/bin/bash
if [ `date +%u` -lt 6  ] && [ `date +%H` == '19' ] ; then
   echo 'Sorry, you cannot run this program today.'
else
   echo 'yes, you can run today'
fi

Note that the [ is just a shorthand for the test command and ] the last argument to it. The && operator is used like in any other command line, for example cd /home && ls

Upvotes: 6

Related Questions