11

Say a file called abc exists in the current directory and it has some text in it. When you execute the command:

cat abc > abc

Why do the contents of the the file abc disappear?
Why does the command delete the text in it and the file becomes an empty file?

  • And for solutions, see Can I make cut change a file in place? – Gilles Aug 29 '16 at 17:48
  • 10
    A laser pointer is a very effective tool for cat redirection. </pun> – WBT Aug 29 '16 at 23:04
  • My cat responds very poorly to redirection... – Ex Umbris Aug 29 '16 at 23:35
  • To avoid this issue, I use a little shellscript which I called dog: cat abc | dog abc – joeytwiddle Aug 30 '16 at 3:22
  • Another option, if you don't mind the output on screen, is to use tee. – Andrea Lazzarotto Aug 30 '16 at 10:14
27

Because of the order how things are done.

When you do:

cat abc > abc

> is the output redirection operator, when the shell sees this it opens the file in truncation mode using O_TRUNC flag with open(2) i.e. open("abc", O_TRUNC), so whatever was there in the file will be gone. Note that, this redirection is done first by the shell before the cat command runs.

So when the command cat abc executes, the file abc is already truncated hence cat will find the file empty.

  • 1
    What about cat abc >> abc ? What happens then? – Tulsi Kanodia Aug 29 '16 at 15:39
  • 2
    @TulsiKanodia - that causes an infinite loop. Each time cat reads a line, it appends another before moving to the next. – user3490 Aug 29 '16 at 16:04
  • 3
    This is detected and prevented. Instead, the text cat: filename: input file is output file (where filename is the filename you chose) is printed on the old stdout. – UTF-8 Aug 29 '16 at 16:52
  • @TulsiKanodia See unix.stackexchange.com/questions/154903/why-does-cat-x-x-loop – Gilles Aug 29 '16 at 17:42
5

Adding to @heemayl's answer, if you want the code to be more clear about the sequence in which things are happening you can simply put the any redirections at the start of the command:

> abc cat abc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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