通配符是咱們在shell環境中不知不覺中都會用到的,有時甚至都不會考慮到去探究其實現過程,由於使用得太廣泛了。而清晰地理解每個過程,將有助於咱們的分析和調試。html
說白了,通配符就是在 shell 環境下用來選擇匹配給定模式的文件簇的特殊字符。下面是一段相對正式的定義,援引自https://bash.cyberciti.biz/guide/Wildcards。shell
Wildcards is one of the most important features of Bash shell. It allows you to select a group of files. For example you can select all C programming files in a GUI file manager with mouse. To select all C programming files in a Bash shell you use wildcards. In short wildcards are nothing but special characters that allows you to select a group of files that matches certain pattern.通配符通常只出如今命令的參數中,當 shell 在參數中遇到了通配符時,會將其當作路徑或文件名區在磁盤上搜尋最可能的匹配,若符合要求的匹配存在,則進行代換,不然就將該通配符做爲一個普通字符傳遞給命令,而後由命令進行處理。bash
以下圖1-1所示爲 shell 進行命令行參數解析時的全過程,很是繁瑣但很重要。app
shell 常見通配符如表1所示。less
而除了有通配符以外,還有一系列特有的特殊元字符,如表2所示。這些元字符基本是做用在命令上面,用做多命令分割或參數分割。要注意這裏的 {} ,由於表1裏面也有相似的字符,實際上他們的做用範圍並不相同,所以不會出現混淆。ide
metacharacter A character that, when unquoted, separates words. One of the following: | & ; ( ) < > space tab另外對於表1和表2中的特殊字符,若是咱們想讓其變成普通字符,就須要使用轉義符,shell中提供三種轉義符,如表3所示。ui
There are three quoting mechanisms: the escape character, single quotes, and double quotes. A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows, with the exception of <newline>. If a \<newline>
pair appears, and the backslash is not itself quoted, the \<newline> is treated as a line continuation (that is, it is removed from the input stream and effectively ignored).Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.
The characters $ and ` retain their special meaning within double quotes. The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or <newline>. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes
is escaped using a backslash. The backslash preceding the ! is not removed.其中單引號與雙引號的區別以下:spa
- 單引號屬於強引用,它會忽略全部被引發來的字符的特殊處理,被引用起來的字符會被原封不動地使用,只是引號範圍內不容許再引用單引號。
- 雙引號屬於弱引用,它會對其中幾個被引用起來的字符作特殊處理,其它的則忽略。例如:
- 其中 $ 加變量名能夠取變量的值;
- 反引號和 $() 括號裏面的字符會被當作命令執行後替換原來的字符;
- 須要使用 $ ` " 時須要經過反斜槓轉義。
參考資料.net
[1] shell腳本【命令解析過程】命令行