In this post, we will see the Linux Commands to create a new file. There are numerous ways to create a new file in Linux.
In the Linux terminal, the touch command does the job to create a new file.
Create a new file with the touch command
Create a file name with the touch command followed by the file name.
touch filename1.txt
If the file with the same name exists, its timestamp will be changed to the current time
To check the file is created using the following command
ls
To Create multiple files
touch filename1.txt filename2.txt filename3.log
You can create a filename with any extension like .txt, .xml, .log, etc.
Create a new file with Output Redirect Operator
Use the > output redirection operator to create a new file.
> newfile.txt
If a file already exists with the name it will overwrite and empty the file.
Creating a new File with cat Command
cat stands for concatenate. It is used to read and concatenate files. We can use it also for creating new files.
cat > file1.txt
To create a new file enter the cat command followed by the right angle bracket and filename.
Creating a new File with echo Command
The echo command is usually used to display a text. The arguments passed are displayed in the standard output.
It can be used with output redirect operator > to output to a file.
echo "Text display" > filename.txt
The above command will output the content to the file.
To just create an empty file, use the following command
echo > filename.txt
Create a new File with printf Command
printf is similar to the echo command but provides more options for the output format than the echo command.
Create a file with a single line of text
printf 'sample text 1\n' filename.txt
With multiple lines
Separate each line with \n newline character.
printf 'sample text 1\n sample text 2' filename.txt
Creating a new File using Heredoc
Heredoc is used to write a block of text/multiple lines of text to a file
Use cat command followed by double left angle bracket(redirection operator) << then EOF limitstring(or delimiter token) and the filename.
cat << EOF > filename.txt
This text will be
written to file by Here Document
EOF
The limitstring EOF won't appear in the output and it denotes the end of the text. You can use any delimiter token instead of EOF.
Note: To create a new file you need to have write permission in the directory.