Linux Commands

How to Create a File in Linux Using cat Command

The cat command is one of the most popular and frequently used commands in Linux-like operating systems. This command allows Linux users to create single or multiple files, display the content of the file and concatenate the files.

The cat command in Linux is mostly used for displaying the content of the files and appending the content of one file to the other file. In this tutorial, we will cover the procedure of creating files in Linux using the cat command.

How To Create a Text File in Linux Using cat Command

You can create a file and add the text into the file through the cat command. Use the following syntax for creating the text file in Linux:

cat > <Filename.txt>

Let’s create a text file named a newfile.txt using the following command:

cat > newfile.txt

Once you executed the cat command the cursor will move to the next line where you can begin adding the text in the file:

Once you are done with writing the text in the file, press Ctrl + D to save the file in the device. Verify the created file by using the following command, it will read the content of the file and display it on the terminal:

cat newfile.txt

How To Create a Bash File in Linux Using cat Command

The cat command can also be used for creating the bash file in Linux. Use the following command syntax on the terminal:

cat > <filename.sh>

I have created a file2.sh via the cat command using the above given syntax:

cat > file2.sh

Next, type the script you want to add in the bash file and display the file via the below given command:

cat file2.sh

If you want to run the script, use the following command:

. file2.sh

How to Redirect the Content of File Using cat Command

The cat command can also be used for redirecting the content from the source file to the destination file. The following command will copy the content of newfile.txt to the file2.txt. If the file2 does not exist this command will create it:

cat newfile.txt > file2.txt

How to Display Line Number with cat Command

Through the cat command you can also display the line number at the start of each line. Use the following command:

cat -n newfile.txt

Conclusion

The cat is one of the most useful and powerful commands of Linux. It is used in Linux for creating, and displaying content of the files. Other than that, cat command can also be used for appending the content of one file to another. In this tutorial, we have discussed the creation of bash and text files in Linux using the cat command and we have also discussed the appending of content from the source to the destination file.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.