Bash Quick Start Guide
上QQ阅读APP看书,第一时间看更新

Shell metacharacters

So far, all of our examples of commands and arguments have been single unquoted shell words. However, there is a set of metacharacters that have a different meaning to Bash, and trying to use them as part of a word causes problems.

For example, suppose you want to create (touch) a new file named important file. Note that there's a space in the name. If you try to create it as follows, you get unexpected results:

$ touch important file

If we list the files in the directory after running this, using ls -1 to put all the names on separate lines, we can see we've actually created two files; one named important, and one named file:

$ ls -1
file
important

This happened because the space between the two words separated them into two separate arguments. Space, tab, and newline are all metacharacters. So are | (pipe), & (ampersand), ; (semicolon), ( and ) (parentheses), and < and > (angle brackets).

There are many other characters interpreted specially by Bash in some contexts, including {, [, *, and $, but these are not considered metacharacters according to the manual page's definition.

Even the error messages can be confusing if you try to use a word with one of these characters in it:

$ touch Testfile<Tom>.doc
bash: Tom: No such file or directory

$ touch Review;Final.doc
bash: Final.doc: command not found

In some cases, you may not get an error message at all, and something very unexpected will happen instead; for example:

$ touch $$$Money.doc
$ ls
31649.doc

A lot of the time we can simply work with files and words that don't use these characters. However, we can't always do that, and we can't just hope others behave the same way—we will eventually have to work with their files and data. How can we include special characters in our words safely?