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?

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

2 Answers 2

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.

4
  • 1
    What about cat abc >> abc ? What happens then? Commented Aug 29, 2016 at 15:39
  • 2
    @TulsiKanodia - that causes an infinite loop. Each time cat reads a line, it appends another before moving to the next. Commented Aug 29, 2016 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. Commented Aug 29, 2016 at 16:52
  • @TulsiKanodia See unix.stackexchange.com/questions/154903/why-does-cat-x-x-loop Commented Aug 29, 2016 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 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.