A Command Line Crash Course

It's time to get acquainted with your command line and learn the commands that you'll actually need to use.

Scroll down...

Content

Resources

Comments

Let's face it -- the command line is a bit intimidating. It's that text-only interface that Hollywood has told us hackers furiously type away on while doing their devious business and the domain of experienced programmers who can effectively communicate in binary. It's time to get over those misconceptions.

The command line (Terminal on a Mac, Command Prompt on Windows) is your window into your computer and your home base for doing development work. It's how you'll be able to jump between files and directories, open stuff up, run simple scripts and check the status of things.

The command line is a very useful place to become familiar with but it actually only takes a dozen or so commands to get there and that's what we'll cover in this lesson. You'll become very familiar with those commands too because you'll be using them constantly.

It can be pretty scary for beginners to open up the command line because it seems like you can mess up your computer by typing the wrong thing but, again, we'll be working well within the safe zone and you've got nothing to fear.

WINDOWS USERS: You might want to jump ahead to the installations assignment and use the "Git Bash" application you'll install there instead of using the default Command Prompt. That way you can be sure all the commands will be the same.

We've packed the Resources tab with links to more stuff (including more advanced commands) but everything you need to start with is covered below. Enjoy!

What is the Command Line?

Command Line Screenshot

The "Command Line" we use is called Bash, or "Bourne-Again SHell" and it's a text-based shell for controlling the computer. It's actually a program itself that gives us a window into our operating system and lets us run commands. We interact with it using a simple scripting language that we type directly onto the prompt.

From the Command Line, you can navigate your file system just like you would by double clicking on folder icons in the Finder. You can also run other programs directly, or even load up a file containing a whole batch of commands to run.

The Command Line is fully text-based, so you'll need to type everything in and can pretty much forget about the mouse. There are some tools that help you visualize things, but you'll have to get onto the Command Line sooner or later to do something. The most important part of learning it, therefore, is getting a good conceptual model of what's going on and using those dozen-or-so commands we'll cover to navigate through it.

For our purposes, we'll use a classic "house with rooms" model to think about the organization of your computer's file system. When you fire up the command line, you'll be in one room and then you'll need to navigate your way to wherever you want to be. Before we get there, though, let's actually locate our command line.

Finding The Command Line

The command line

For Mac users, you'll need to find the Terminal program. There are several ways to locate it:

  1. Find the terminal icon (pictured above) in your applications dock at the bottom of your screen and click it.
  2. Find it inside your "Applications" folder, which can be found in the topmost directory of your hard drive.
  3. Type CMD + SPACE or click the magnifying glass in your top right corner to open up the "Spotlight" application and then just type "Terminal". It should be the first result.

For Windows users, open the "Command Prompt" window by clicking the Start button, clicking All Programs, clicking Accessories, and then clicking Command Prompt.

If you've installed Git Bash with the Rails Installer, it will be in the "RailsInstaller" folder:

Git bash location

Taking a Look Around

Now that you've got your command line open, we're going to take a look around.

Helpful Notes I

First, a few notes about the command line:

  • Whenever we talk about the command line, we'll use the dollar sign $ to indicate the prompt. If you need to type something, only type the stuff after the dollar sign. For instance, if we say to type $ echo "hello world", you just type echo "hello world". Often there is other information to the left of the prompt (which we'll help you set up shortly), so it's conventional to abbreviate the prompt as $.
  • Type commands directly after the prompt and hit enter to execute them.
  • Many commands will have options that you can specify, which are preceded by a dash -, e.g. $ ls -a, where -a is an additional option for the ls command. Options are, well, optional, so you don't always see them.
  • Many commands will take arguments, which come after any options (if present).
  • When you run commands, there is rarely any feedback that you were successful. If the prompt just shows up again on the next line, that's a good sign -- it was successful. This takes some getting used to!
  • Capitalization matters! Documents and documents are not the same thing.
  • Spaces matter! You'll quickly learn to omit spaces in your file and folder names because they're a pain to type on the command line -- you have to "escape" them with an extra backslash \, so My Folder Name becomes My\ Folder\ Name. Otherwise it'll think you're passing multiple arguments or commands.

Man Pages (and Google) as your Map

What happens when you want to know what a command does or forget what options are available? For that, we use the "man" (manual) pages. It's a command that you can feed any other command to and it'll bring up the help for it. Alternatively, you could just Google it.

This is the man page for the ls command, achieved by typing $ man ls:

Windows: help

Man pages man page

Three key parts to look at:

  1. The first lines contain a brief description of the command
  2. The "Synopsis" section gives the format that the command will take, including the order of any options and arguments. Anything in brackets [like_this] is optional.
  3. "Description" section gives more specifics, including what exactly each option does.

Scroll down with the arrow keys to see more or press q to quit.

We'll use the man pages to explain the coming commands a bit more.

Where are we now?

Now we're ready to poke around a bit.

Your Current Directory

Type pwd to see what our current working directory is... or basically "where am I now?" Mine outputs /Users/eriktrautman/Documents/test, yours might vary depending on your name and where you are.

View Directory Contents

To see the contents of your current directory, use ls. You should see a bunch of folder and/or file names listed. Check out its man page with $ man ls!

Use the a option with ls, i.e. $ ls -a, to see not just the normal files and folders in your current directory, but also the hidden ones. Hidden file names are preceded by a period . and are usually things that normal users shouldn't mess with. There are a few that you'll get particularly familiar with in the coming weeks.

You can pass ls the l option for "long", which outputs a lot more information about each file or folder. There are several interesting columns, but the one to the left, which might look like -rw-r--r--@, represents the permissions for a given file. We won't cover file permissions here, but check out the flossmanual on permissions if you'd like to learn more.

Terminal ls command

You can pass multiple options by just combining them, e.g. $ ls -la.

Open a File or Directory

Finally, if you want to open a file or directory, just use the open command! It will open in whatever default application you've previously set up (so folders open in the Finder). For instance, $ open . will open the current folder in your familiar Finder window.

Windows: start

Directories

You're probably familiar with file directories, e.g. ~/Documents/some_folder/some_other_folder/some_file.txt, from navigating your filesystem using the graphical Finder. They are alive and well on the command line, and you'll spend plenty of time navigating through them. A few quick points about directories:

  1. No matter which directory you're in, you should see at the top the . and .. directories. . represents your current directory, or, to use the house analogy, your current room. .. is the door to the folder which contains your current folder, or basically going "one level up". For instance, if you are currently at ~/Documents/eriktrautman then .. represents ~/Documents.
  2. The tilde (~), top left on your keyboard, represents your home directory.
  3. When you enter a command and pass it a directory, it starts looking at the current directory (pwd) by default. So if you type $ ls some_folder it will show you the contents of some_folder if it exists within the current folder.
  4. If you want to play with a file in another directory, you can either specify it relative to the current one by using .. to go "up" and normal syntax to go "down" (e.g. ../../some_folder_two_folders_up/some_file.txt) or you can specify it absolutely from the root directory by using the ~ (e.g. ~/Documents/your_username/some_folder/some_file.txt).

Try looking at the contents of nearby directories using absolute and relative paths and the ls command.

Helpful Notes II

Here are a few more helpful pointers now that you're able to look around:

  • When you're typing file names (and many other things) on the command line, use the TAB key to autocomplete the word. This will save you tons of time. It will automatically fill in the remainder of the word once you've typed enough to uniquely identify it.
  • Pressing the UP key will cycle through the history of recently used commands. Very handy.
  • $ clear clears out all the recent output, though you can still scroll up to see it.
  • To jump to the beginning of a line, use CTRL + a.
  • To jump to the end of a line use CTRL + e. These may not seem too helpful yet since you're entering only very short commands but it saves a lot of time when you copy-paste longer strings or cycle through a previous command and want to change something at the very beginning.
  • Use CMD + TAB to jump between applications on your computer.
  • Within the Terminal, use CMD + n to open a new window and CMD + t to open a new tab. Use tabs! It'll save heartache.
  • Use CMD + SHIFT + LEFT ARROW or RIGHT ARROW to cycle between tabs within a terminal window.
  • Use CMD + LEFT ARROW or RIGHT ARROW to cycle between the terminal windows.
  • Whenever you've opened a dialogue on the command line (e.g. when you use the man command), just press q to quit. This is conventional for pretty much anything.
  • If you're executing a command that's in an infinite loop or your somehow stuck, use CTRL + c to break the cycle. This is a good way to get out of anything the q key won't jump you out of.

Let's Move Around

Okay, you know where you are and you can look around. Let's move around! That's the job of the cd command (for "Change Directory"). Check out its man page!

Change Directories

Use cd .. to go up one, or pass it the path to any other directory to jump into it.

If you want to go back to your home directory, type either cd ~ or simply cd.

Try jumping around to different directories and then displaying their contents with ls.

You can open the files with the previously-mentioned open command. If you want to specify the exact application to use for opening a file, use open -a TextEdit foo.txt. Note that foo is what we usually call example filenames.

Let's Make and Destroy Stuff

You're a pro at navigating and inspecting directories, now let's make and destroy files and directories.

Make a Directory

Check out the man page for mkdir -- it lets us create a new folder. Just pass it a name or path, and POOF the directory is created. The -p flag lets us nest folders. For example, $ mkdir -p testdir/inner_folder creates two folders, one inside the other. Try it!

Make A File

Now create a new file called test.txt using the touch command. touch gently touches the file... if the file exists already, it just updates the "last modified" date to the current date and time. If it doesn't exist, touch will create the blank file.

Open a File

Now open test.txt using the open command. Specify the TextEdit program if you must. Type something into it and save it. I've typed just Hello World! into mine.

View a File from the Command Line

Now if we want to read the file and dump its contents into the terminal, use the cat command. For example, $ cat test.txt outputs Hello World! for me.

Rename or Move a File

The "Move" command, mv will let you either rename a file (by "moving" it to the same location but with a different name) or actually move it (by specifying a different target directory). Check out the man page for some of the options, but basically it takes the name and path of the current file then the name of where you want it to go.

For example, $ mv test.txt test2.txt will rename the file. If we first create a new directory $ mkdir new_folder then type $ mv test2.txt new_folder/test2.txt, it will put test2.txt into it.

Copy a File

Use cp to copy a file to a new location or name, with the same syntax as mv.

Note that both cp and mv can be destructive because, if you try to move a file onto one that already exists, it will do so without warning you. Use the -i option to make sure it warns you if you're about to overwrite something.

Try copying and moving your test files around.

Remove a File or Directory

Speaking of destructive commands, if you want to intentionally remove a file, pass its path and/or filename to the rm command. So $ rm test.txt will remove that file.

You won't be able to remove a directory that contains files unless you pass it the -R option. Only do this if you're absolutely sure! This is one of those commands that can delete a lot of files very quickly from your hard drive...

The Super User

Some files on the computer are protected. You wouldn't want just anyone to be able to change some of the core commands on your system, right? Sometimes, like during an installation, you come across these files or commands (you'll probably get an error message to that effect).

That's why there's the concept of the "Super User", who has the power to do anything. Use the sudo command prior to any other command to run it as the "Super User". That's you, but you need to remind your computer by entering your administrator password.

When you enter passwords on the command line, it won't look like anything is being typed but don't worry, it is. The lack of output is for your protection too.

Beyond Basics: Chaining Commands Together, Redirection and Piping

We've just covered all the commands you'll need to use for a long time but that doesn't mean that there aren't more helpful ones out there. We can chain commands together by passing the output of one into the input of another using piping | or redirection >. This lets you do things like searching through, sorting, or combining files.

Though interesting and helpful, these aren't necessary for you to know off the bat. If you're curious, check out the following lessons from Floss Manuals and follow along:

  1. Standard Files
  2. Redirection
  3. Piping

...Or take their entire course :)

OMG Where the hell am I?

Here's an uncommon but really confusing situation. You've typed a command and it popped up a text dialogue that looks somewhat similar to the man pages one except q and CTRL + c aren't letting you quit. What's happening?

You've probably opened it up in the VIM text editor, which is created specially for advanced developers. It has its own syntax, so don't panic. Either come back here and look at the following commands or just google "How do I quit VIM?".

From the first result on Stack Overflow:

  1. Hit the ESCAPE key; that goes into command mode. Then you can type:
    • :q to quit
    • :q! to quit without saving
    • :wq to write and quit
    • :x to write and quit
    • :qa to quit all

Now go back about your business in peace.

So How Does It Work?

So now you're pretty comfortable with the command line. A basic understanding of how it works will help you customize it in the next lesson and should give you a better mental model of what's going on.

Essentially, when you start a new command line window, you're firing up a configuration file and logging into the shell. That configuration file has some handy stuff that you'll get to edit later.

$PATH and Environment Variables

The Bash shell keeps track of information using environment variables denoted by the dollar sign $. You can see all of them by typing the $ printenv command. It's a bunch of output, but you should be able to look through them and see some you can figure out. One of them that you'll get familiar with is the $PATH variable.

The $PATH variable has a listing of all the directories Bash should search through whenever you give it a command in order to figure out what exactly the command does. They will be separated with colons :. If you've just installed something and are getting error messages saying it can't be found, odds are that you need to add that application's location to your $PATH variable.

If you want to know which location a given command or program is running from, use the which command. For instance, if you type $ which open, it outputs /usr/bin/open, which is where the binary code for open lives. We'll use which in the future to verify which version of certain programs you are using.

.bash_profile

When Bash first opens up, it looks for a configuration file called .bash_profile. That file can contain commands and variables that help you to configure the shell properly.

You may not have a .bash_profile file yet! If you've already skipped ahead and installed the necessary software, you probably created it but it doesn't actually exist yet by default. You'll be creating it from scratch in the next lesson regardless.

See if you have the bash profile by checking in ~/.bash_profile. If you do, open it up to see what's in it. Remember you'll need to use the -a option on ls to see the hidden files.

Note: If you want to show hidden files in your finder, check out this blog post from OSXDaily

Over time, you'll get a bit more familiar with (and make additions to) the contents of this .bash_profile file, which probably seems a bit odd at the moment. It's not something you'll use every day, just something that's helpful to know so you get a better idea of what you're doing.

We've packed a lot into this lesson and there's more available if you're still hungry. Check out the Resources tab for more information about the Command Line and also about how your computer actually works. For a good start, browse through the presentation below.



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

The Command Line

How Your Computer Works

Learn About Your OSX Machine

Sorry, comments aren't active just yet!

Next Lesson: Configure Your Command Line