Ubuntu provides a number of command line tools to create new files. In this Answer, we'll try the following ones to create files.
The touch
command
The output redirection operator (>
)
The cat
command
The echo
command
touch
commandtouch
is perhaps the most commonly used command-line tool used to create files in Unix-like systems. It is pretty straightforward and can be used to create one or more empty files in a single line:
touch filename1 filename2
We can create files with any extension using touch
. In the following example, we demonstrate creating some text and Python files using this command:
>
)>
is called the output redirection operator and is used to redirect the output of a process to a file. The same operator can also be used to create empty files using the following syntax:
> filename
Here is an example:
cat
commandThe cat
command, in addition to displaying the contents of a file, can also be used to create new files when combined with the output redirection operator (>
):
cat > filename
The added benefit of the cat
command is that it also allows adding content to the newly created file. After executing the command, enter the desired text and press "CTRL+C" to save the content and exit:
In the above image, we first create a new file named hello.txt
, add a few lines of text, and press "Ctrl+C" to save and exit. We then verify that the file was indeed created using the ls
command, and verify the contents of the file using cat hello.txt
.
echo
commandecho
is another command line tool that can be used to create files, with or without content. To create a file with no content, use the following syntax:
echo > filename
To create a file with a single line of text, use the following syntax:
echo text_to_add > filename
To create a file with multiple lines of text, use the -e
switch with the echo
command. The -e
switch allows backslash escape interpretation, and we can then use \n
to create new lines:
echo -e "First line\nSecond line\nThird line" > filename
Below is a demonstration of creating files using the echo
command:
The terminal given below runs Ubuntu operating system. Click the terminal to connect and try creating various files using all of the listed commands:
Free Resources