Typically I create files using the vi editor. vi, unlike just about any other editor in the *nix world, is ubiquitous –even when running in stripped down systems and in single-user mode, so it’s worth knowing how to use for basic editing. The great thing about vi is that the more you work with it (and spend time learning about it) the more you discover it can do to make your life easier. I will write more about this in another post.
In addition to vi, another way I quickly create files on *nix systems is with touch.
$ touch newfile.txt
This creates an empty file that you can later append info or edit, what have you. Touch can change an existing file’s timestamp without altering the original file’s contents too, in fact that may be touch’s raison d’etre, but I almost always use it to create new, empty files when I need to (or when I need to test the umask settings of the user I’m logged in as).
Another quick and dirty file creation method is with simple I/O redirection. To create a new, empty, file:
$ >newfile.txt
To create that file with a blurb in in,
$ echo blurb > newfile.txt
(newfile.txt will contain the world blurb), or
$ echo “Longer blurb with more words than the original one we created” > newfile.txt
(the sentence in quotes will be in the file. Note: with I/O redirection, the > character will overwrite/clobber the contents of the file on the “less than” side of the operator, so be careful when using this that “newfile.txt” or whatever you’re redirecting to doesn’t have anything important in it….or you can use >> to append, rather than overwrite/clobber the file.
This is cool, and you can do a lot with the echo command and escape sequences that will allow you to do some level of formatting with the contents of the new file. But if you need formatting why not use an editor, or editor-like functionality? Leaving vi and other editors aside, the simple cat command (short for concatenate) with some I/O redirection can be pretty cool, and not quite as overkill as the full vi editor (and perhaps a few less keystrokes from start to finish).
$ cat > newfile.txt
(creates the file, but you are still concatenating, so…)
type your message/write your script here
create a new paragraph if you like
get fruity with formatting if you need
^D (ctrl + D) to terminate with EOF (end of file)
Voila, you have a file with the contents you just typed in cat mode. It’s nothing fancy, but if you want to whip up a quick and dirty script, it’s one way to get started.
Pretty stupid stuff, huh?