Bash Create Files
1. Creating Empty Files with touch
The touch
command is primarily used to change the access and modification timestamps of a file. However, if the specified file does not exist, touch
will create an empty file with that name. This makes it ideal for creating placeholder files.
If my-file.txt already exists, its timestamps will be updated to the current time. If it doesn't exist, it will be created as an empty file.
To verify whether the file's timestamps were actually updated, you can use the stat
command.
Creating Multiple Empty Files At Once
Options with touch
-a
- Update only when the file was last read-m
- Update only when the file was last changed-t
- Set the timestamp to a specific time-c
- Do not create any files
Learn more about these options
2. Creating Files with Content using Redirection
The most common way to create a file and populate it with content in one go is by using output redirection operators (>
, >>
).
>
(Redirection / Overwrite): This operator redirects the standard output of a command to a file. If the file exists, its content will be overwritten. If the file does not exist, it will be created.>>
(Append Redirection): This operator redirects the standard output of a command to a file. If the file exists, the new content will be appended to the end of the file. If the file does not exist, it will be created.