Files and folders

The truncate command

Changes a file's size: it trims it or extends it to the size you give.

Syntax

truncate -s <tamaño> <archivo>Try it in the terminal →

Most useful options

-s, --size <tamaño>Size in bytes. With + it extends, with - it reduces, and < or > set a maximum or a minimum
-c, --no-createDoes not create the file if it does not exist
-r, --reference <RFILE>Takes the size of another file
-o, --io-blocksReads the size in I/O blocks, not in bytes

Copy-ready examples

$ truncate -s 10 notas.txtsets the file to 10 bytes. If it does not exist, it creates it.
$ truncate -s +100 registro.logadds 100 bytes at the end, which read as zeros.
$ truncate -r original.txt copia.txtgives copia.txt the same size as original.txt.
$ truncate -c -s 1M no-existe.txtwith -c it does not create the file and prints no warning.
$ truncate -s 0 notas.txtWARNING: empties the file and deletes its content without asking. Make a copy first.

You can try them in the browser terminal: it does not touch your computer.

Common errors

MessageCauseFix
truncate: you must specify either '--size' or '--reference'You called truncate without giving either a size or a reference file.Add -s with the size, or -r with a reference file.
truncate: Invalid number: 'abc'The -s value is not a valid number: it has letters that truncate does not recognise as a unit.Write the number with its unit, for example 10K or 2M.
truncate: cannot open 'subcarpeta' for writing: Is a directoryYou passed a folder. truncate only changes the size of files.Give a file inside the folder.

Typical mistakes

  • If the file does not exist, truncate creates it. To avoid that, use -c.
  • If the new size is smaller, whatever is left over is lost without a warning.
  • Without a unit, the number is bytes. K and M are powers of 1024; KB and MB are powers of 1000.

Differences from similar commands

  • dd: copies data between files or devices block by block. truncate only changes the size.
  • stat: shows the size and blocks of a file without changing it.
  • rm: deletes the whole file. truncate -s 0 leaves it empty and keeps the name and permissions.

Related commands

FAQ

How do I create a file of an exact size for testing?

With truncate -s 10M test.bin. It is created with 10 mebibytes of null content.

Can I use one file as the size reference for another?

Yes, with -r: truncate -r original.txt copia.txt leaves copia.txt with the same size as original.txt.

Does a file I extended with truncate take more disk space?

Not necessarily: the added part is a sparse hole that reads as zeros, and the file system does not have to allocate blocks for it.

Learn to actually use it

The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.

Start the free course