3
  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?

Tim
  • 101,790
  • May cat bk |tee bk or less bk |tee bk help you? (in general <text-processing-command> file1 |tee file1) – Pandya Nov 06 '14 at 05:33

1 Answers1

6

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.

Hauke Laging
  • 90,279