Bash 脚本,while 循环中的多个条件 [英] Bash scripting, multiple conditions in while loop

查看:29
本文介绍了Bash 脚本,while 循环中的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在使用两个条件的 bash 中获得一个简单的 while 循环,但是在尝试了来自各种论坛的许多不同语法之后,我无法停止抛出错误.这是我所拥有的:

I'm trying to get a simple while loop working in bash that uses two conditions, but after trying many different syntax from various forums, I can't stop throwing an error. Here is what I have:

while [ $stats -gt 300 ] -o [ $stats -eq 0 ]

我也试过:

while [[ $stats -gt 300 ] || [ $stats -eq 0 ]]

... 以及其他几个结构.我希望这个循环继续,而 $stats 是 >300 或者如果 $stats = 0.

... as well as several others constructs. I want this loop to continue while $stats is > 300 or if $stats = 0.

推荐答案

正确的选项是(按推荐的升序):

The correct options are (in increasing order of recommendation):

# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]

# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]

# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]

# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]

# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))

# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))

一些注意事项:

  1. 引用[[ ... ]]((...)) 中的参数扩展是可选的;如果未设置变量,-gt-eq 将假定值为 0.

  1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

(( ... )) 中使用 $ 是可选的,但使用它有助于避免意外错误.如果 stats 未设置,则 (( stats > 300 )) 将假定 stats == 0,但 (($stats > 300 )) 会产生语法错误.

Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.

这篇关于Bash 脚本,while 循环中的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆