I've noticed that when writing a shell script, there's a lot of inconsistency in whether people put a space after the I/O redirection operators. For example:

foo >bar.txt

Will work, but so will this:

foo > bar.txt

....and even this:

foo       >             bar.txt

In fact, even the Linux Documentation Project page is frustratingly inconsistent about it - using 2>&1 (which doesn't actually work in my Bash terminal with spaces) in one place and > filename in another!

I've always used the former, as the latter feels like 2 different arguments to me, but I was wondering: Is there any difference or reasoning between the two?

Is >bar.txt more portable than > bar.txt or something? Or should I use 1 syntax in 1 defined situation, and the other in another?


1 Answer 1

  1. The characters <, >, &, and | are special to the shell and are recognized with their special meaning in any position when not quoted.

  2. The portable redirection operators are >, >>, >|, >&, <, <<, <<-, <>. A redirection operator may be preceded with a number indicating a file descriptor; in this case there can be no space between the number and the redirection operator; and the number must be separated from the previous word, if any, with one or more spaces. Other than that, unquoted spaces around the redirection operators are optional.

See The Open Group Base Specifications Issue 7, 2018 edition, Shell and Utilities, chapter 2, "Shell command language" for details.

Not the answer you're looking for? Browse other questions tagged or ask your own question.