在使用一些命令時(如:ls、git),剛好遇到一些需求是想很方便地遍曆所有的目錄和檔案,後來經過搜尋,終於找到了一個“神奇”的萬用字元 “**”(兩個星號),在設定了Bash的globstar選項後,**就可以匹配任當前何目錄(包括子目錄)以及其中的檔案。所以,瞭解了一下 globstar這個選項,當未設定globstar時,**萬用字元的作用和*是相同的,而設定了globstar後,**的匹配範圍不同了(更廣一些)。注意:globstar是Bash 4.0才引入的選項,之前的老版本是不支援的,使用“bash –version”可產看當前使用的Bash的版本。
關於glob這個詞,我也覺得好奇,中文不好解釋,大致就是“對萬用字元展開”的意思,如下的英文吧:
In shell-speak, globbing is what the shell does when you use a wildcard in a command (e.g. * or ?). Globbing is matching the wildcard pattern and returning the file and directory names that match and then replacing the wildcard pattern in the command with the matched items.
在bash的man page中,對globstar的說明提到只兩次,說的都是同一件事情,如下:
代碼如下 |
複製代碼 |
Pathname Expansion ...... * Matches any string, including the null string. When the globstar shell option is enabled, and * is used in a pathname expansion context, two adjacent *s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a /, two adjacent *s will match only directories and subdirectories. ...... globstar If set, the pattern ** used in a pathname expansion context will match a files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match. |
寫了個測試和學習globstar的shell指令碼如下:
代碼如下 |
複製代碼 |
#!/bin/bash <pre lang="Bash"> function show() { for i in ** do echo $i done } cd /root/jay/ echo "------------------------" echo "disable globstar option:" # globstar is disabled by default shopt -u globstar show echo "------------------------" echo "enable globstar option:" shopt -s globstar show
執行上面測試globstar的shell指令碼,看它的輸出結果,就很容易理解globstar了,如下:
[root@smilejay jay]# ./test_globstar.sh ------------------------ disable globstar option: dir1 dir2 file1 file2 index.html test_shopt.sh ------------------------ enable globstar option: dir1 dir1/file3 dir2 dir2/file4 file1 file2 index.html test_shopt.sh |