无法解释bash脚本中的语法错误

时间:2016-04-12 17:09:30

标签: bash if-statement syntax-error

在我的脚本中,我写下了这个控制表达式:

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

startend是简单的数字。文件rooms.txt中的每条记录都是以这种方式构建的:

room;date;start;end;username

记录中有非空格。 当我运行脚本时,我在if语句附近遇到语法错误。

有人能告诉我错误在哪里吗?感谢

1 个答案:

答案 0 :(得分:4)

“{和}”的运算符-a[[ ... ]]条件无效。请改用&&

但是如果你在bash中进行数字比较,那么使用(( ... ))代替[[ ... ]]可能会更有意义。那么普通的关系运算符是数字而不是基于字符串的,因此您可以使用>代替-gt

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

但是,只有rooms.txt只有一行时,此方法才有效;否则,当$(cut...)命令生成多个数字时,您将收到语法错误。我不确定你正在解决什么问题,但这样的方法可能会很有成效:

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