2

I accidentally ran the following scripts in Bash:

$ ls -l | > ../test.txt

And I got an empty test.txt.

What happened?

Mat
  • 202,337
  • 40
  • 393
  • 406
cqzlxl
  • 23
  • 2

2 Answers2

3

You ran a null command, i.e. a simple command with just one or more redirections. This performs the redirection but nothing else.

>file

is a way to truncate file to zero bytes. A null command ignores its stdin, which is why you don't see the ls output. I believe POSIX leaves this undefined (in fact, zsh reads stdin when you type >file). There is an explicit null command named : (colon). Null commands are useful if you just need them for their side effects, i.e. redirection and variable assignment, as in

: ${FOO:="default value"}  # Assign to FOO unless it has a value already.
Jens
  • 69,818
  • 15
  • 125
  • 179
  • 1
    [What Is the Purpose of the `:' (colon) GNU Bash Builtin?](http://stackoverflow.com/questions/3224878/what-is-the-purpose-of-the-colon-gnu-bash-builtin) – cqzlxl Jan 06 '13 at 11:22
0

> ../test.txt empties the file despite of the input data that's why you've got 0-sized file.

AlecTMH
  • 2,615
  • 23
  • 26