Different ways to create a file in *nix
Table of contents
You can create files in many ways, and we will go through most common ones.
echo
echo 'muffins!' > file
This method creates a file containing whatever echo
outputted (in our case, it's muffins!
). It works well, but be wary, it will overwrite an existing file.
If you want to create an empty file instead, you can use -n
:
echo -n > file
A note for ZSH users: if you have
noclobber
set, then>
won't overwrite files by default.
touch
touch file
This method is different than any other listed here, as touch
is intended to be used as a timestamp utility.
It will either create an empty file, or change the timestamp of the existing one to current time.
true
and :
:> file
# and
true > file
This is the shortest way to create an empty file or empty an existing one.
Both :
and true
are commands that simply exit without any errors, and since they don't output anything, >
creates a file, but has nothing to put inside it.
Conclusion
There are many ways to create a file. You may choose any of the methods above, all of the methods are common and efficient, just don't forget that you can also check if the file exists using [[ -f "file" ]]
๐