除了基本的*
,?
和[...]
模式之外,Bash shell還提供擴展模式匹配運算符,如!(pattern-list)
(「匹配除給定模式之一以外的所有模式」)。需要將extglob
shell選項設置爲使用它們。一個例子:如何在引用的表達式中轉義擴展路徑名擴展模式?
~$ mkdir test ; cd test ; touch file1 file2 file3
~/test$ echo *
file1 file2 file3
~/test$ shopt -s extglob # make sure extglob is set
~/test$ echo !(file2)
file1 file3
如果我通過一個殼表達到執行它在副殼的程序,操作者將導致錯誤。這裏的直接運行一個子shell測試(在這裏我從另一個目錄執行,以確保膨脹不會過早地發生):
~/test$ cd ..
~$ bash -c "cd test ; echo *"
file1 file2 file3
~$ bash -c "cd test ; echo !(file2)" # expected output: file1 file3
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `cd test ; echo !(file2)'
我已經試過各種逃避的,但沒有我已經拿出了正確的工作。我也懷疑extglob
不在一個子shell設置,但事實並非如此:
~$ bash -c "shopt -s extglob ; cd test ; echo !(file2)"
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `cd test ; echo !(file2)'
任何解決方案感謝!