How to use the command line – Part 1 (IP&CS #3)



Today we are going to control the wonderful beast that is the computer. However, we are not going to jump straight into programming, per se. Instead, we are going to spend some time looking at how to use the command line.

This is my preferred strategy for a few reasons, which I shall explain momentarily. If you’re not familiar with what the command line is, that’s ok, most people aren’t.  

Put simply, the command line is an alternate way of instructing your computer what to do — achieved through text-based commands. This differs from the typical way we control our computers, using the mouse and GUI (briefly discussed last time).

Learning the basics of the command line, before doing programming, is my preferred approach for two reasons.

Firstly, I think this an easier way to get a sense of what programming feels like. With the command line, you type cryptic commands, which must be syntactically correct, and then the computer does something. Programming, too, is like this.

With the command line, however, instructions you type are (typically) shorter. Additionally, you will be performing actions that are already familiar to you. Today, we will mostly focus on moving around your computer, as well as a few other things. This keeps the informational overhead to a minimum.

Secondly, after these two instalments on the command line, we will be setting up our programming environment. You can still do this while basically avoiding the command line all together, but it seems like unnecessary effort. It makes more sense to me that we jump into it from this direction. But this isn’t just in an attempt to expend less effort. This is also an investment for what’s to come.

Finally, one of the programming languages we will be working with will be compiled. Again, this will be easier if you’re familiar with the command line.


CLI101

The command line interface — or command line, CLI etc. — is the application that allows you to interact with the system using written commands.

On Macs you do this using Terminal. On other operating systems, you use something else. Alternatively, if you use Windows, then you won’t have a standard command line program. You will need to download some additional software to gain that ability.

Regardless, for this post I’m just going to talk about Macs — as that’s what I have. If you don’t have a Mac, sorry. Google some stuff that is relevant to your situation and go from there.

Moving on…

As I said, the command line is an alternate way of controlling your computer. It allows you to do pretty much all the things you do already, using the mouse and all the aesthetic icons. Only difference is that it trims the fluff. This ability to interact directly with the computer’s operating system, without the extras, allows for very powerful and efficient management of your computer!

However, sometimes fluff is useful — I’m glad my Ugg boots and robe are covered in it. So, with that said, not all tasks are best suited to the command line. Some tasks — typically relating to visual aesthetics, such as photo or video editing — are more easily completed through the GUI. Therefore, please consider the command line as the metaphorical drill. Soon you can use it in combination with the GUI, your metaphorical hammer.


Finding the CLI

To find your command line interface, simply use Mac’s Spotlight Search. You could do this by moving your mouse and clicking the magnifying-glass icon in the top-right corner of your display. Or, you could use your keyboard.

For the moment, let’s consider mouse = bad and keyboard = good. Therefore, let’s go with the latter option. It’s easy, I promise, the keys are right next to each other.

To bring up the search function, just press ‘command + space’. Meaning, press them both at the same time — though pressing command slightly beforehand is more practical than aiming for identical timing.

If you press space marginally before command, an action will typically be performed. Whereas pressing command first doesn’t do anything — it basically just says to the computer, “Whatever I press next should be interpreted differently to when it is normally pressed (when not holding down the command-button).”

This is because command is a modifier. For example, in a Word document pressing the Z-key writes the letter ‘z’. Pressing ‘command + Z’ undoes the most recent change.

Ok, so now that you’ve got your technique down for bringing up the search function, do that.

Next, type in the following letters: t… e… r… m… i…

Ok, you get that, too.

Depending on your computer-savviness, this might be a slow process at the start. However, you begin to bundle all these movements together and do it automatically over time — you develop that “muscle memory” as people like to say, much to my frustration.

For example, when I have the thought, “I need the terminal for this,” I will instinctively perform all the aforementioned steps in a coherent sequence. I’ll press command + space, type ‘t e r’ and hit return. This brings up the terminal in less than a second and with minimal conscious thought.

That’s the cool thing about learning. Things become intuitive, unconscious, automatic.

And while this may seem trivial, the point I’m trying to make is that things become easier. The same, too, will be true when it comes to difficult programming concepts. The first time you write a for-loop you think, “How in the heck am I going to remember all of this?” — yet a week later you can do it half-asleep.


What does the command line look like?

Like this.

Default terminal window

Well, mine does.

Yours might look slightly different, but most of that is aesthetic and not functionally important.

Though, that’s not quite true. In order to make yourself feel much more like a programmer, I would recommend selecting Terminal in the top left menu, then Preferences then double clicking on your favourite of the colour schemes. You may need to exit the app and reopen it to see the changes take place, but nobody wants to be operating a command line they don’t like the look of… This is important stuff.  

However, I would warn against the highly customised look, with the underscore-cursor and neon lime-green text. I thought that looked proper hardcore for a while but, ultimately, it was just such a pain to look at and try to decipher when my eyes had gotten tired.

Now I just use the standard ‘Pro’ option — though I don’t yet use it like a pro. I also make the default font size slightly larger. Again, the eyes.

Have a play around. See what you like best!  


Controlling the CLI

The first two things you want to be aware of with the command line interface is the prompt and the cursor.

The cursor is the mouse of the terminal. When you do things, those things will be done in the location of your cursor. This is probably intuitive for you at this point, though, as most text-based applications make use of something similar. In which case, I won’t spend much time on it. To be explicit, however, the cursor in the above image is the grey rectangle.

The prompt is a little more interesting.

The prompt basically tells you who the user is and the location that the terminal is operating in (though these display settings can be adjusted). This is then followed by the percentage sign ( % ), which separates the prompt from the commands you type as a user.

Using the above image again, the user is LJPurcell@Lyndons-MBP and the location is shown by the ~ (tilde). The tilde is shorthand for the home directory/folder.

We can change this second part of the prompt by executing a command that moves us into a different location on the computer.

Terminal window showing one successful command

See how the prompt on the second line has the same user, but expresses a different location?

Pretty neat.

Let me explain what I did here. I gave a command, and then a (file) path.

The command cd stands for change directory — which basically just means move around. Directories are the same thing as what we typically call folders, so I’ll use the two terms interchangeably (though, directory is the preferred term in tech-circles). The path is then used to tell the computer where exactly to go.

In essence, “I want you to move and here’s where I want you to move.”

The above shows me moving from my home directory, represented by the tilde — shorthand, in this instance, for /Users/LJPurcell — to my desktop and then from there into a folder named ThereforeThink.

Not too tricky, right?

It’s important to note, though, how exactly I specified moving into the ThereforeThink folder. You might at this point wonder: Could Lyndon have just typed cd ThereforeThink ?

Good question. Let’s try that now.

First, we will need to move back to our home directory. You can do this by executing cd and nothing else.  This command will always take you to your home directory.

From there, I’ll try the command that attempts to jump straight into the ThereforeThink directory.

Terminal window showing three successful commands and one error

No luck.

Let’s break the above image down into lines, as well as location and command:

  • Line #1
    Location – Home directory.
    Command – Move from the home directory to the Desktop and then from there into the ThereforeThink directory.
  • Line #2
    Location – ThereforeThink directory.
    Command – Return to home directory.
  • Line #3
    Location – Home directory.
    Command – Move from the home directory into the ThereforeThink directory.
  • Line #4
    Error (more on this momentarily).
  • Line #5
    Location – Home directory still, due to unsuccessful previous command.
    Command – Nothing as of yet.

This is then some empirical evidence that I cannot jump straight from my home directory into the ThereforeThink directory. The error message is particularly confusing because we know that it exists! Furthermore, as I highlighted, you can jump – from anywhere – back into your home directory.

This is all seems highly suspect and inconsistent…


Visualising the path

The two issues of confusion can be resolved quite quickly through visualising what is happening. We will do this using a common structure in computer science: the tree graph.

A simplified version of the layout of my folders and files is as follows. As you will see, the structure of my computer system is hierarchical (discussed here).

Tree graph showing the contents of my computer

With this, we can see more clearly why we were getting the results that we were. When in the home directory, and we tell the computer “Go to the ThereforeThink directory,” it – rightly – says in return, “I don’t know what you’re talking about!”

That is what the cryptic error message cd: no such file or directory: ThereforeThink is telling us. A similar message would occur if I tried to jump straight into the CS Series directory, or open up one of the text files contained within in it.

The error message is only cryptic if you don’t know how to parse it, though. What it is doing is relaying back to us which command caused the issue ( cd ), why this command was an issue ( no such file or directory ) and what exactly we were looking for that didn’t exist ( ThereforeThink ).

This is useful for diagnostic purposes, because when you are stringing many commands, paths and other options together, you want to have a clear idea of what the issue was when something doesn’t work.

This may be confusing, but the key point is that your terminal will only know a few basic things about navigating its way around your computer — where it is currently, what stuff is in that location, as well as the path it took to get there. This last part is why we can always rely on a jump back to the root directory to be successful — but not necessarily a jump to another location — because the root directory is always part of the path we took to get to wherever we are currently.

It might help to think of the locations in your computer as analogous to areas of a house you’ve just walked into for the first time.

Let’s consider the opening hallway is equivalent to the home directory. From there you can see a door into the study, or a path that leads into the kitchen. But until you go into the kitchen, you don’t know about the living room or the outdoor entertaining area, as well as what’s in those rooms or where you can get to from there.

Tree graph showing the contents of my a hypothetical house

Remember something I said previously: computers are dumb – they have no inferential ability.

Even if you have been to this house before, you still can’t teleport straight from the Opening Hallway to the Hammock. You need to go from the Opening Hallway to the Kitchen to the Outdoor Area, and then to the Hammock.

A computer is the same. It needs to follow a path. As such, you need to specify to the computer what series of movements, from location to location, it needs to make. A path is how we do just that. It uses forward slashes (on a Mac) to separate locations. The slashes are like the doors from room to room.

As such, the aforementioned route through the house could be represented in your terminal in one of the following ways, from most verbose to concise:

  • Opening Hallway/Kitchen/Outdoor Area
  • ~/Kitchen/Outdoor Area
  • Kitchen/Outdoor Area

Then, once you’re in the Outdoor Area location, you might execute something like the open Hammock command.


A few extra tips

On the topic of paths, there are other shorthand methods we can use for manoeuvring through directories.

For example, a period ( . ) refers to the directory you’re currently in — also known as your working directory.

A double-period ( .. ) refers to the parent of your current working directory — which is the folder “one up,” or that your current directory “sits within.”

As such, these pieces of notation can be used to refer to directories that are in a relative position to whatever your current working directory is. It doesn’t matter whether you have moved through two, or ten, directories to get where you currently are. If you need to go back out of the directory you are in currently and into another (moving up only one level and across into a different one) you could use the ../ path, rather than type out the full name of whatever that directory is called.

The terminal is supposed to help with efficiency, right? Why waste time typing names!

That is why the next tip — command line completion — is such a beautiful thing. If you type in the first few letters of a command, directory, or file, and then press the tab-key, the terminal will autocomplete your entry — providing two criteria are satisfied.

The first is that something within that location must begin with what you have typed in. For example, if I was in my Desktop, typed a command and then the letter ‘z,’ I could hit tab as many times as I like, but nothing will happen. I have nothing in that location that starts with z.

The second criterion is that you can’t have multiple things within that location that start with the letter, or string of letters, you have entered so far. Again, taking my Desktop as the location, if I type ‘cd P’ and then press tab — hoping for autocomplete — I don’t get much on the completion side of things.

This is because I have three possible locations:

  • PersonalDocuments (for self-explanatory things)
  • PhilosophyAu (for podcast related things)
  • ProfessionalDevelopment (again, for self-explanatory things)

I do, however, still get some help offered to me, even if there remains work to be done. The help is that the terminal displays the names that are causing it to have issues with tab-completion.

Terminal window showcasing tab-complete collision

In this case, I only need to type ‘e’ or ‘h’ or ‘r’ and then I can hit tab once more, and the rest will be filled in immediately.

Also of note, the forward slash at the end of the names indicates that each of those things is a directory, as opposed to a file (such as a word document or a script of code).

In fact, as one of our final terminal tricks, let me show you that now.

If we press return given the above state — before completing the rest of the cd P command — we will bring up a familiar type of error. We’ve already covered that, though, so let’s keep moving.

Next, I want to create a file that has a name beginning with ‘P’ to highlight the difference between files and folders when displayed by the command line.

To create a new file, we use the command touch followed by the name of the file, and its extension — if we want it to be anything other than a boring old document file.

However, for our purposes it’s sufficient to create just a text document, which I will name ‘P’ to make it clash with the other directories. You can see how I did this using the touch command in the image below.

Then, once more I’ll enter the command cd P and hit tab for autocompletion. As expected, though, no bueno…

Terminal window showcasing tab-complete collision, with added file

This highlights the point I wanted it to.

With this we can see more clearly that the terminal does, in fact, discern between files and directories. Of the things in my Desktop that begin with a capital-p, there are three directories (denoted by the trailing forward-slash) and a text file (denoted by the extension .txt).

If you’ve been following along and typing in the commands yourself in your own terminal, you can remove that superfluous P.txt file by executing the command rm P.txt — where rm stands for remove, if you couldn’t guess.

Finally, you can wipe your terminal clear by typing clear and hitting return.

And with that, it’s like you were never there!


Much more…

Today we covered the basics of the command line. Which, for us Mac-users, is the Terminal app. I hope this gave you a sense of what not only it can do, but also — as per our original intensions — what programming feels like.

Next time, we will cover some more about the terminal, enhancing your power to wield it. Then, we move onto programming.

Don’t discount what you’ve learned so far, though — by no means is it all in vain. You are thinking and learning about computer science already at this point. Additionally, the fluency you are building with the command line will only make for a smoother programming journey.

Have a practice and play around a bit. You might be surprised with what you figure out.

Thanks for reading.

I am fascinated by the power of knowledge; in particular, how through its implementation we can build a better life for ourselves and others. Most specifically, I am interested in ideas related to rationality and morality. I believe we can all be benefited by having a concern for both probability as well as people. As a student, I am studying Artificial Intelligence. As a professional, I work in mental health case management. When I am not doing one of these things, I am very likely writing for my blog, recording an episode for the "PhilosophyAu" podcast, hanging out with my nan, reading a book or, occasionally, attending a rave. A previous version of myself obtained a bachelors and a masters degree in sport science and was the Manager of Educational Services for a leading health and fitness company.

Related Posts

Leave a Reply