简体   繁体   English

Bash-如何区分控制运算符和元字符?

[英]Bash - How to discriminate control operator from metacharacter?

According to bash manual : 根据bash手册

control operator

A token that performs a control function. 执行控制功能的令牌。 It is a newline or one of the following: '||', '&&', '&', ';', ';;', '|', '|&', '(', or ')'. 它是换行符或下列其中之一:'||','&&','&',';',';;','|','|&','('或')'。

metacharacter

A character that, when unquoted, separates words. 当不加引号时,用于分隔单词的字符。 A metacharacter is a blank or one of the following characters: '|', '&', ';', '(', ')', '<', or '>'. 元字符是空格或以下字符之一:'|','&',';','(',')','<'或'>'。

Many characters are both control operator and metacharacter . 许多字符既是control operator又是metacharacter

So how could I konw the syntax category of eg a ; 所以我怎么知道例如a的语法类别呢; ?

Take if COND ; then CMD ; fi if COND ; then CMD ; fi if COND ; then CMD ; fi if COND ; then CMD ; fi as an example. if COND ; then CMD ; fi为例。

; seems like a control operator in the context, for it can be substituted by newline . 在上下文中似乎是一个control operator ,因为可以用newline代替它。 However removing pre and post space s around ; 但是删除前后的空间 ; still works ok. 仍然可以。 Isn't it supposed to be separated by sapces if it's an operator ? 如果它是运算符,不是应该用空格分隔吗?

According to the bash manual, an operator is: 根据bash手册, operator为:

A control operator or a redirection operator . 控制运算符重定向运算符 See Redirections, for a list of redirection operators. 有关重定向运算符的列表,请参见重定向。 Operators contain at least one unquoted metacharacter. 运算符包含至少一个未引用的元字符。

The metacharacter is basically any character that cannot be part of a word. 元字符基本上是任何不能作为word.一部分的word.

Definition of word : word定义:

A sequence of characters treated as a unit by the shell. Shell将一个字符序列视为一个单元。 Words may not include unquoted metacharacters. 单词可能不包含未引用的元字符。

There is no need for spaces around operators because they always contain metacharacters , which makes the parser know it is not part of the word . operators不需要空格,因为它们始终包含metacharacters ,这使解析器知道它不是word一部分。

An exception is redirection , where eg redirection是一个例外,例如

ls 2>&1

requires a space prior to the redirection statement since the operator has a parameter 2 , and requires the parameter to be next to the operator (otherwise it will be a parameter to ls ). 由于操作符具有参数2 ,因此在重定向语句之前需要一个空格,并且要求该参数位于操作符旁边(否则它将是ls的参数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM