Skip to content

Linux Quickie: Truncate Files, Keep Permissions

Are you looking for a way to truncate files in Linux, without losing the set permissions and ownership? Learn how in this quickie! 

Normally you would truncate files with a command like $ sudo rm file && touch file

The problem with this command is, that it deletes the file and creates a new one. With new standart permissions and ownership. But we want to keep them. How?

Truncate Files, Keep Permissions with cat

With cat!

Just use $cat /dev/null > file and the content of the file will be removed, not the file itself (file beeing the path to the file).

Explanation

cat copies the standard input and returns it to the standard output. Now we just use /dev/null as input and copy it into our file as output. Et voila, our file is empty.

 

Published inLinuxQuickies

2 Comments

    • Zanidd Zanidd

      The resulting file is not empty but contains an empty line. This would break log files like wtmp that store fixed width records.

Leave a Reply

%d bloggers like this: