Creating Files Using the Command Line

Trying to do a simple post a day can be quite difficult, I have found. Thinking up new and original content is nigh impossible everyday, and while I have a dozen or so major articles and tutorials in the works, today is going to be something simple.

To this end today I have decided to talk about creating files in the command line.

There are many options, although three come to mind, each with there specific purposes.

The first is using a command line file editor. I like to use vim, but you could use nano or vi or any other editor. To create a file you enter the name of the editor followed by the file name.

vim myfile.txt

You can now write anything into the file and when you exit (every editor has different save and exit commands but vim is :w to save and :q to exit). This method of file creation is useful when you want to insert many lines of code into the file when you create it. If you want to create a file in a specific location you can put the path to the location before the file name like so

vim /path/to/location/myfile.text

You may also need to sudo the command if you do not have write permissions in the location.

If you need to create a file and only enter a single line you can use the echo command. Normally echo prints the command to the next line, however with a directional command we can echo the single line to a file.

echo enter this line > myfile.text

Again if you need to create a file in a different location for example /etc/default/dhcp then not only will you need to add the file path, you must also use sudo

sudo echo enter this line > /etc/default/dhcp/myfile.text

This is a really useful command, but what if you need to create a file but don’t need to add anything to it. To do this we have the touch command. Simply type the file name after the touch command. Of course the same rules apply for creating the file in a specific location.

touch myfile.text

I hope that this has been helpful, These commands are very commonly used in the terminal when working with Linux.

Advertisements
Leave a comment

2 Comments

  1. Great post about this. I’m surprised to see someone so educated in the matter.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: