sentientmachine
sentientmachine

Reputation: 357

Can't explain syntax error in bash script

In my script I wrote down this control expression:

if ! [[ $start -gt $(cut -f3 rooms.txt) -a $end -gt $(cut -f4 rooms.txt) ]]; then
    echo "Invalid prenotation";
    ./prenote.sh;
fi

start and end are simple numbers. Each record in file rooms.txt is built in this way:

room;date;start;end;username

There are non blank spaces in the record. When I run the script I get a syntax error near the if statement.

Can someone tell me where the error is? Thanks

Upvotes: 0

Views: 41

Answers (1)

Mark Reed
Mark Reed

Reputation: 95252

The operator -a for "and" is not valid in [[...]] conditionals. Use && instead.

But if you're doing numeric comparisons in bash, it might make more sense to use ((...)) instead of [[...]]. Then the normal relational operators are numeric instead of string-based, so you can use > instead of -gt:

if ! (( start > $(cut -f3 rooms.txt) && end > $(cut -f4 rooms.txt) )); then
...
fi

However, this approach only works if rooms.txt has only one line; otherwise, you'll get syntax errors when the $(cut...) commands produce more than one number. I'm not sure exactly what problem you're solving, but an approach something like this might be fruitful:

while read _ _ low high _; do 
  if ! (( start > low && end > high )); then
    ...
  fi
done <rooms.txt

Upvotes: 4

Related Questions