bash
defines several metacharacters. From man bash
:
metacharacter
A character that, when unquoted, separates words. One of the following:
| & ; ( ) < > space tab
Because metacharacters separate words, it does not matter whether they are surrounded by spaces. The pipe symbol, |
, is a metacharacter and hence, as you noticed, it does not need spaces around it.
Note that [
, ]
, {
, }
, and =
are not metacharacters. Their meaning, by contrast, depends strongly on whether they are surrounded by blanks.
Examples of when spaces are and are not needed
As you noticed, it does not matter whether |
is surrounded by spaces. Let us consider some examples that commonly confuse bash users. Consider:
$ (date)
Sun Mar 1 12:47:07 PST 2015
The parens above force the date
command to be run in a subshell. Because (
and )
are metacharacters, no spaces are needed. By contrast:
$ {date}
bash: {date}: command not found
Since {
and }
are not metacharacters, the shell treats {date}
as one word. Instead of looking for the date
command, it looks for a command named {date}
. Because it doesn't find one, an error results.
Another common problem is the test
command. The following works successfully:
$ [ abc ] && echo Yes
Yes
Remove the spaces and an error occurs:
$ [abc] && echo Yes
bash: [abc]: command not found
Because [
and ]
are not metacharacters, the shell treats [.bashrc]
as a single word and the result, just like in the date
example, is an error.
Assignment statements are also sensitive to spaces. The following assignment is successful:
$ v=date
$ echo $v
date
Add a space and the assignment fails:
$ v= date
Sun Mar 1 12:55:05 PST 2015
In the above, the shell temporarily sets v
to empty and then executes the date
command.
Add a space before =
also causes a failure but for a different reason:
$ v =date
bash: v: command not found
Here, the shell attempts to execute the command v
with the argument =date
. The error is because it found no command named v
.
|
pipe or;
semicolon are used by most shell (bash, ksh, tcsh) as separator of commands. when not enclosed in quote white space before and after are irrevelent.