2

This question already has an answer here:

  1. Redirection is not allowed here. Is cat not allowing? But isn't redirection independent of any command running with it?

    $ cat bk > bk
    cat: bk: input file is output file
    
  2. Why does the following redirect empty the file:

    $ less  bk > bk
    

    awk also works in the similar way as less in regard to redirection. awk is the one with which I actually found the problem, while the above examples are meaningless

In general, what are the right way to use redirect?

marked as duplicate by don_crissti, Networker, jasonwryan, Ramesh, slm Nov 5 '14 at 1:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • May cat bk |tee bk or less bk |tee bk help you? (in general <text-processing-command> file1 |tee file1) – Pandya Nov 6 '14 at 5:33
5

The problem is that the output redirection kills the file before less is even started:

open("file", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
dup2(3, 1)                        = 1
close(3)                          = 0
execve("/usr/bin/less", ["less", "-WNS", "file"], [/* 102 vars */]) = 0

The normal output redirection overwrites the file. The O_TRUNC (see man 2 open) deletes the file content.

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