Brace Expansion

A concept closely related to pathname expansion is brace expansion. Whereas pathname expansion wildcards will expand to files and directories that exist, brace expansion expands to an arbitrary string of a given form: an optional preamble, followed by comma-separated strings between braces, and followed by an optional postscript. If you type echo b{ed,olt,ar}s, you'll see the words beds, bolts, and bars printed. Each instance of a string inside the braces is combined with the preamble b and the postscript s. Notice that these are not filenames—the strings produced are independent of filenames. It is also possible to nest the braces, as in b{ar{d,n,k},ed}s. This will result in the expansion bards, barns, barks, and beds.

You can also use a slightly different type of brace expansion for creating a sequence of letters or numbers. If you type echo {2..5} you'll see this expands to 2 3 4 5. Typing echo {d..h} results in the expansion d e f g h.[11]

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Brace expansion can also be used with wildcard expansions. In the example from the previous section where we listed the source, object, and header files in the working directory, we could have used ls *.{c,h,o}.[12]

 


[6] Most UNIX tutorials say that root has the name /. We stand by this alternative explanation because it is more logically consistent with the rest of the UNIX filename conventions.

[7] Each directory also has the special directory . (single dot), which just means "this directory." Thus, cd . effectively does nothing. Both . and .. are actually special hidden files in each directory that point to the directory itself and to its parent directory, respectively. root is its own parent.

[8] MS-DOS and VAX/VMS users should note that there is nothing special about the dot (.) in UNIX filenames (aside from the leading dot, which "hides" the file); it's just another character. For example, ls * lists all files in the current directory; you don't need *.* as you do on other systems. Indeed, ls *.* won't list all the files—only those that have at least one dot in the middle of the name.

[9] Specifically, ranges depend on the character encoding scheme your computer uses (normally ASCII, but IBM mainframes use EBCDIC) and the character set used by the current locale (ranges in languages other than English may not give expected results).

[10] This is different from the C shell's wildcard mechanism, which prints an error message and doesn't execute the command at all.

[11] This form of brace expansion is not available in bash prior to Version 3.0.

[12] This differs slightly from C shell brace expansion. bash requires at least one unquoted comma to perform an expansion; otherwise, the word is left unchanged, e.g., b{o}lt remains as b{o}lt.