How to create file in linux


#1

Transfered from Linux Config Disqus comments:

Question:

What is the best way to create a file in Linux. The file should be empty and it should be regular text file. I tried “create file” command but it did not work !
Answer:
The general way to create file is to use touch command. To create a file called create-file using touch command we can do:

$ touch create-file This file will be empty and its name will be create-file . However, this is not the only way how you can create a file in Linux . Here are some other ways on how to create a file in linux:

Create file using echo command:

$ echo "" >  create-file 

Create file using redirection:


$ > create-file 

Create file by copying /dev/null:

$ cp /dev/null create-file 

If you wish to create a file with certain content you can use echo command.

$ echo my new created file > create-file 

This will create a file called create-file with a “my new created file” content. Other way how to create a file in Linux with some content in it is to use vi editor ( or any other text editor will do ):

$ vi create-file 

This will create a file when you save from within vim editor. You can also create some dummy file with a certain data size. For example the command below will create a file with size 200 MB in size:

dd if=/dev/zero of=create-file bs=1M count=200 

In Linux there is also way to create a file with a huge size and taking no space. Let’s create a file with size of 2TB:

$ df -h .
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda1              72G   20G   51G  29% /
$ dd bs=1 seek=2TB if=/dev/null of=create-file
0+0 records in
0+0 records out
0 bytes (0 B) copied, 2.0464e-05 s, 0.0 kB/s
$ ls -lh create-file 
-rw-rw-r--. 1 lilo lilo 1.9T Mar 17 16:20 create-file
$ df -h .
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda1              72G   20G   51G  29% /

#2

#3

#4