cqzlxl
cqzlxl

Reputation: 23

What happens when pipe char directly followed by the redirection in Bash?

I accidentally ran the following scripts in Bash:

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

And I got an empty test.txt.

What happened?

Upvotes: 2

Views: 63

Answers (2)

Jens
Jens

Reputation: 72619

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.

Upvotes: 3

AlecTMH
AlecTMH

Reputation: 2725

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

Upvotes: 0

Related Questions