Reading and creating files and folders

Now that we know how to change directories and move around the filesystem, let's look at the basic file and folder operations from the CLI. In general, whatever you can do from your GUI, like the MacOS finder is also possible on the command line. Indeed if we're looking to create multiple files or observe the last lines of a certain file — like a logfile — the terminal might be the better choice!

Creating and reading files

To create a new file we can use the touch command followed by the filename we want to generate. Note that we also have to specify the file's extension. This also works if you're not looking to create a text file or anything else that can be easily handled from within the console, like an mp4.

command line
touch test.txt

A very handy advantage over most GUIs is the ability to create multiple files at once, using touch combined with filenames in curly braces (globbing). On top of that, we can use loops (more on that in another chapter) to create a lot of files with the same naming patterns and such in just one short command.

command line
touch {a,b}.txt
ls -l
-rw-r--r-- 1 ben staff 0B Nov 10 19:24 a.txt
-rw-r--r-- 1 ben staff 0B Nov 10 19:24 b.txt

If we want to read files we have a lot of options to choose from. The command line gives us very powerful editors like vi, vim, and nano that can all be used to read and write files. However, if we don't want to leave our prompt there is a way to print a file's content right to our terminal and that's cat.

command line
cat test.txt
Here is the content of out test file, displayed directly on the cli.

When dealing with log files that can be especially large, we often want to look at only the last few lines of a file. Luckily the CLI allows us to do just that easy as well, by using the tail command and passing the -n flag, specifying how many lines from the bottom of the file we want to look at.

command line
tail -n 3 test.txt
Lorem ipsum dolor sit amet, consetetur sadipscing elitr
Sed diam nonumy eirmod tempor invidunt ut labore et dolore
This is the last line of test.txt

Creating a directory

Similarly to creating a file, we can use the command line to create folders, using the mkdir command, followed by the new folder's name. You can also add more folders, separated by a whitespace and they will all be created at the same time. No need to use braces here, like we needed when creating multiple files.

command line
mkdir my-new-folder

There is also a very handy option -p that will ensure that every other, not yet existing folder in a given path is also created when issuing mkdir. So in the following example the folders parent, child, and grandchild will be created, even if parent and / or child don't exist yet.

command line
mkdir -p parent/child/grandchild