One reason you have a mysterious Unix file called 2
(or 1
)
Suppose, one day, that you look at the ls
of some directory and
you notice that you have an odd file called '2
' (just the digit).
If you look at the contents of this file, it probably has nothing
that's particularly odd looking; in fact, it likely looks like
plausible output from a command you might have run.
Congratulations, you've almost certainly fallen victim to a simple typo, one that's easy to make in interactive shell usage and in Bourne shell scripts. Here it is:
echo hi >&2 echo oop >2
The equivalent typo to create a file called 1
is very similar:
might-err 2>&1 | less might-oop 2>1 | less
(The 1
files created this way are often empty, although not always,
since many commands rarely produce anything on standard error.)
In each case, accidentally omitting the '&
' in the redirection
converts it from redirecting one file descriptor to another (for
instance, forcing echo
to report something to standard error)
into a plain redirect-to-file redirection where the name of the
file is your target file descriptor number.
Some of the time you'll notice the problem right away because you don't get output that you expect, but in other cases you may not notice for some time (or ever notice, if this was an interactive command and you just moved on after looking at the output as it was). Probably the easiest version of this typo to miss is in error messages in shell scripts:
if [ ! -f "$SOMETHING" ]; then echo "$0: missing file $SOMETHING" 1>2 echo "$0: aborting" 1>&2 exit 1 fi
You may never run the script in a way that triggers this error condition, and even if you do you may not realize (or remember) that you're supposed to get two error messages, not just the 'aborting' one.
(After we stumbled over such a file recently, I grep'd all of
my scripts for '>2
' and '>1
'. I was relieved not to find
any.)
(For more fun with redirection in the Bourne shell, see also how to pipe just standard error.)
|
|