0

I want to make a oneliner loop that reads and checks what it read.

This surely won't work:

while [[ read line != "q" ]]; do; echo "enter q to quit: "; done

Zsh here tells me condition expected: read.

Perhaps read does not even have this concept of a return value.

4

2 回答 2

2

Bash 陷阱#9

如果接受命令。[ 是一个命令,而不是 if 语句的语法标记。它等价于 test 命令,只是最后一个参数必须是 ]。

[[不是if条件的特殊语法。[[本身就是一个命令。尝试这样的循环:

while read -r line; do
  [[ $line = "q" ]] && break
  # more code
done

read当它无法读取表达式并且[[是命令时返回失败,所以这有效。有关详细信息,请参阅http://mywiki.wooledge.org/BashFAQ/001

注意:将-r开关添加到read是一个好主意 - 它可以防止输入中的反斜杠发生有趣的事情。

于 2013-04-24T05:56:33.533 回答
-1
while read line; do; [[ "$line" == 'q' ]] && break; done;

似乎工作。

但我不确定为什么我不能用 替换[[ ]][ ]它奇怪地失败了:

$ bash
bash-3.2$ while true; do; read line; [ "$line" == 'q' ] && break; done;
bash: syntax error near unexpected token ';'                                       

$ while true; do; read line; [ "$line" == 'q' ] && break; done;
ajlfkj
zsh: = not found
于 2013-04-24T05:52:59.093 回答