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

Can't explain syntax error in bash script

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

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 语句附近出现语法错误。

谁能告诉我错误在哪里?谢谢

"and" 的运算符 -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