Alternate to copy + remove

is there any single command for

cat file1 > file2
cp /dev/null file1

The original file must retain intact but it should get empty. Actually, the contents needs to be processed by another process and for new entries, the file must remain there with zero records.

Try

mv file1 file2 && touch file1

I need a single command, can't lose the file placement even for a ns.

The following is faster - while still two commands

cp file1 file2
>file1

Note, however, that you have a built-in race condition...
If someone opens file1 for appending during the cp and then writes to that file descriptor:

  • the data may be copied into fie2 by the cp ,
  • may be cleared by the > /dev/null never to be seen again,
  • or may appear in file1 after it has been cleared by the > /dev/null .

To get rid of this race condition, we need to know more about how processes writing to file1 open the file and how the permissions of processes writing to that file are related to the owner and group of the directory in which the target file resides.

The writers obviously have write permission to the target file. If they also have write permission in the directory in which it resides, the safe thing would be to use:

mv file1 file2

and have the writers open file1 with the flags:

fd = open("file1", O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);

guaranteeing (assuming no write errors) that data written to that file descriptor will appear either in file1 or file2 .

If you can't do that; you need to block all writers to file1 while it is being rotated.