if fi [: 参数太多 [英] if fi [: too many arguments
问题描述
这个脚本有问题吗?
if [ grep -q "#<filter>" /etc/hosts ] && [ grep -q "#</filter>" /etc/hosts ] ; then
echo "exist"
fi
它显示的错误是:
[: too many arguments
推荐答案
问题在于您将普通命令包装在 [
语法中.这是无效的.[
标记实际上是一个命令,它将其参数解释为一种非常有限的表达式语言,用于进行字符串和数字比较以及文件和目录的条件,例如与类型、存在、时间戳.
The problem is that you are wrapping ordinary commands in the [
syntax. This is not valid. The [
token is actually a command, which interprets its arguments as a very limited expression language for doing string and numeric comparisons, and conditions on files and directories, such as tests having to do with type, existence, timestamps.
在 shell 语法中,您可以将一系列命令括在 (...)
括号中.这样做的效果是在新的子进程中运行包含的命令.您还可以使用大括号对命令进行分组以创建组命令.
In the shell syntax, you can wrap a sequence of commands in (...)
parentheses. The effect of this is to run the enclosed commands in a new child process. You can also group commands with braces to create a group command.
&&
和 ||
命令具有相同的优先级;它不像 C 语言中的类似排序.基本上,如果你有一个命令,你可以使用 || 附加另一个命令另一个命令
或&&另一个命令
.||
运算符表示:如果此处左侧的所有内容都失败,则运行以下命令.这样做,否则如果失败,就这样做".&&
操作符的意思是:如果到目前为止一切都成功了,还请执行以下操作.
The &&
and ||
commands have equal precedence; it is not like the analogous sequencing in the C language. Basically if you have a command, you can tack on another command using || another command
or && another command
. The ||
operator means: run the following command if everything to the left of here failed. "Do this, or else if it fails, do this". The &&
operator means: if everything succeeded so far, also do the following.
如果你想要像 (A || B) && 这样的逻辑(C || D)
-- 换句话说,A、B、C 和 D 必须按该顺序运行,并且您希望每个 ||
组中至少有一个命令成功,可以用这样的大括号来完成:
If you want logic like (A || B) && (C || D)
-- in other words, A, B, C and D must be run in that sequence, and you want at least one command in each ||
group to succeed, that can be done with braces like this:
{ A || B; } && { C || D; }
或者带括号,如果您不介意为了控制评估而分叉子进程.请注意,组命令语法中需要分号;否则必须使用换行符,并且大括号周围必须有空格.
or with parentheses, if you don't mind forking child processes just to control evaluation. Note that the semicolons are required in the group command syntax; or else newlines must be used, and there must be whitespace around the braces.
没有大括号,A ||住宿加早餐旅馆C||D
与 A || 意思相同{ B & &{ C ||D;} }
:它本质上是具有同等优先级的右结合.而且,顺便说一下,&
运算符(后台作业)具有较低的优先级 A ||住宿加早餐旅馆C||D &
意味着将整个该死的东西放在后台,而不仅仅是 D
.
Without the braces, A || B && C || D
means the same thing as A || { B && { C || D; } }
: it is essentially right associative with equal precedence. And, by the way, the &
operator (backround job) has a lower precedence A || B && C || D &
means to put the whole darn thing in the background, not only D
.
这篇关于if fi [: 参数太多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!