When working on Linux, knowing how to create files from the terminal could come in handy. There are multiple ways to create a file in Linux. Let’s go over these one by one.
How can you create a file in Linux?
Many commands apart from the touch command also serve a secondary purpose of being able to create a file if it doesn’t exist. We’ll take advantage of that functionality of the commands and use those to create files for our purpose. Let’s start with the first one!
1. The touch command
The easiest and the most straight forward way is by using the touch command followed by the file name.
$ touch filename
Make sure to use the extension of the file you want to create. Touch command can also create multiple files in the same command.
2. The cat command
Cat command, short for concatenation can also be used for creating files. It lets user add text into the file at the time of creation.
$ cat > filename
It is common to use cat command to view the contents of the file as well. To view the contents of a file use the command :
$ cat filename
3. The echo command
Echo command prints out text to the terminal. It can also create files if used along with redirection operator.
$ echo "This is the text" > filename
Here we also see how cat command displays the content of the file.
4. Redirection Operator (>)
Redirection operator when used along with other Linux commands, directs the output towards a particular destination file. We can see its use with grep command. Grep command is used to search for patterns.
$ grep This file.txt > new_file1.txt
Try using the redirection operator with other commands like the ls command. Remember that it will only redirect the output that would normally appear on the terminal screen.
5. Using a text editor
Text editors like Vim and Vi are common in Linux for editing files. You can use these to create a file in Linux as well. If you mention a file that does not exist then the editor will first create the file.
$ vim filename
That’s a wrap!
These were some of the ways you can use to create a file in Linux. Try using the redirection operator with other commands. It is useful when you have to save the output from a command.