Overwrite or Truncate Files in Linux

These are the easiest ways to overwrite and truncate files in Linux.

153 views
d

By. Jacob

Edited: 2023-05-14 08:52

One of the easiest-to-remember ways to overwrite a file completely, emptying its contents, is to just > /path/to/file.txt – but you can also use echo to write an empty string to the file. E.g: echo "" > /path/to/file.txt.

The shortest way to overwrite file:

> /path/to/file.txt

Note. Some shells may use : > /path/to/file.txt instead – the : is a shell builtin that does not return anything.

Truncating the file:

truncate -s 0 /path/to/file.txt

Using a single greater than sign will completely overwrite the file:

echo > /path/to/file.txt

Using (>>) double greater than will append the output to the end of the file:

echo "Added to the end of file." >> /path/to/file.txt

Safety nets and noclobber

If noclobber is set, bash will attempt to prevent you from accidentally overwriting files and potentially loosing data, in that case you will get an error message like this in the console:

-bash: test.php: cannot overwrite existing file.

noclobber is a safety feature that helps to prevent you from doing something potentially catastrophic. To get around that, you may use the following syntax instead:

echo >| /path/to/file

Similarly you can create aliases for commands like mv and cp to run them interactively -i – this is also known as "prompt before overwrite":

set -o noclobber
alias copy='cp --interactive'
alias move='mv --interactive'

If you then try to copy or move a file to a directory that already has a file with the same name, an error message like this will be shown:

cp: 'test.txt' and '/home/ubuntu/test.txt' are the same file

If you want this extra safety net, just include it in your ~/.bashrc or ~/.zshrc file.

Truncate vs echo

Truncating a file is going to be better when someone might be working on the file, as they will not have to reopen the file, and can just continue to use their file pointer.

truncate -s 0 /path/to/file.txt

Tell us what you think:

  1. Understanding file permissions in Unix / Linux based systems, and how to make files immutable.
  2. How to search a directory and subdirectories for a given string of text in Linux with the grep command.
  3. Worth knowing in order to make a bootable USB memory stick with Windows on from Linux.
  4. This is why I decided to encrypt my new Flash Drive, and why I think you should too.
  5. About the problem with using sudo with graphical programs in Linux.

More in: Linux Tutorials