2

I'm pretty new to Linux in general, so I'm not too familiar with do's and don'ts of some commands.

I wanted to create a file and noticed that:

touch file.txt `

creates a file, but so does:

echo >> file.txt

and also

> file.txt

The files created with ">" and "touch" are both 0 bytes but the file created with "echo" is 1 byte.

Why are the files different sizes and what's the best way to create a file? When should someone create a file with "echo" instead of "touch" or ">"?

3

For the general question about creating files, see: Why isn't there any shell command to create files?


With both > file and echo >> file, the shell creates the file if it didn't already exist.

With > file, the file is truncated if it already existed. No command was specified, so nothing gets written to the file and the file will be empty.

echo, without any arguments, prints an empty line. So the output contains the line ending character, typically linefeed (LF, \n):

% echo | od -c
0000000  \n
0000001

So with echo >> file, you get one byte written to the file. If the file already existed, then it would have one byte added to it, because you used >> (append) instead of > (overwrite).

touch creates a file if it didn't already exist, and updates the timestamps on it otherwise. touch doesn't change the contents of the file, so if it already existed and had some contents in it, the contents would remain the same after touch.

Which you want to use depends on what effect you want.

1

muru's answer nicely explains the differences in behaviour.

Depending on what you want, there could be multiple ways to achieve the exact same thing. In that case it can be a matter of "taste", or readability. I prefer touch. It is arguably safer - in case the file already exists, and you did not want to lose its contents. It is also memorable.

If you are writing commands in a script, the general rule is that people read code more times than you write it. I.e. you are communicating with humans - including your future self - and not just the computer :-). You might find the following line of code a bit non-obvious.

> file

If you need the exact same behaviour as > file, there is also a command named truncate. truncate is provided by GNU coreutils.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.