Unix shell 使用 Bash 中的 globstart 選項使用教程

來源:互聯網
上載者:User

在使用一些命令時(如: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
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.