An Introduction to the Command Line
A gentle, hands-on guide to help you get comfortable with the most fundamental tool for developers. No experience required.
Preface
This course was created to give students just enough skill at the command line to tackle more advanced topics. Many people learning to code don't have a basic grasp of the command line interface, which can be a hurdle. This guide is designed to be completed in a day or a week, giving you the foundation you need. It's not a masterclass in system administration, but a quick, practical introduction for newcomers.
Introduction: Shut Up and Shell
This is a crash course in using your computer's command line to perform tasks. It's not as detailed as other books but is designed to get you capable enough to use your computer like a programmer does. By the end, you'll be able to use the basic commands that are part of every shell user's daily toolkit. The most important advice is simple: just type everything in. If you have an irrational fear of the command line, the only way to conquer it is to face it head-on.
You will not destroy your computer. Learning the command line is essential if you want to learn to code. It's like a simplified version of a programming language, teaching you how to control your computer with text commands. Once you're comfortable with this, you can move on to writing code.
How to Use This Course
Your Learning Process
The best way to use this course is to follow these steps:
- Get a small paper notebook and a pen.
- Do each exercise exactly as you're told.
- When you read something that doesn't make sense, write it down in your notebook. Leave space to write an answer later.
- After you finish an exercise, review your questions. Try to answer them by searching online or asking a knowledgeable friend.
You Will Be Memorizing Things
You will be asked to memorize things. This is the quickest way to become capable. For some, memorization is painful, but it's an important skill. Fight through it.
Here's how to memorize things effectively:
- Commit to it. Don't look for shortcuts. Just sit down and do the work.
- Use index cards. Write the command on one side and its description on the other.
- Drill daily. Spend 15-30 minutes every day quizzing yourself. Separate the cards you get wrong and focus on those.
The goal of memorization isn't to learn abstract concepts; it's to ingrain the basics so they become intuitive. Once these fundamentals are second nature, learning more advanced topics becomes much easier.
4. The Setup
Getting Started
This first exercise is about getting your command line interface—also known as a Terminal, Shell, or PowerShell—open and ready to use.
On macOS
- Hold down COMMAND and press the spacebar.
- When the search bar appears, type: terminal.
- Click on the Terminal application.
- To keep it handy, right-click (or CTRL-click) its icon in the Dock, and select Options > Keep In Dock.
On Windows
We'll use PowerShell, which is more powerful than the old `cmd.exe`. For Windows 7 or later:
- Click the Start menu.
- In the search box, type: powershell.
- Press Enter.
On Linux
If you're using Linux, you likely already know how to find your terminal. Look for an application named "Terminal" or "Shell" in your menus.
Important Notes
You may have friends who recommend other shells like `zsh`. For now, ignore them. The goal here is to learn the basics, and the specific shell doesn't matter at this level. Also, be very careful about taking advice from strangers on the internet. Some people think it's funny to trick newcomers into running commands that can damage their system (like rm -rf /). Only get help from people you trust.
Do More: Memorize These Commands
Create index cards for these commands and drill them daily. This will build your core vocabulary.
| Command | Description |
|---|---|
pwd | print working directory |
hostname | my computer's network name |
mkdir | make directory |
cd | change directory |
ls | list directory |
rmdir | remove directory |
pushd | push directory |
popd | pop directory |
cp | copy a file or directory |
mv | move a file or directory |
less | page through a file |
cat | print the whole file |
rm | remove a file |
grep | find things inside files |
find | find files |
man | read a manual page |
apropos | find what man page is appropriate |
env | look at your environment |
export | export/set a new environment variable |
exit | exit the shell |
sudo | DANGER! become super user root |
| Command | Description |
|---|---|
pwd | print working directory |
hostname | my computer's network name |
mkdir | make directory |
cd | change directory |
ls | list directory |
rmdir | remove directory |
pushd | push directory |
popd | pop directory |
cp | copy a file or directory |
mv | move a file or directory |
more | page through a file |
type | print the whole file |
rm | remove a file |
select-string | find things inside files |
dir -r | find files |
help | read a manual page |
echo | print some arguments |
set | export/set a new environment variable |
exit | exit the shell |
runas | DANGER! become super user |
5. Paths, Folders & Directories (pwd)
Do This
The pwd command stands for "print working directory." It shows you your current location in the file system. A directory is just another name for a folder.
$ pwd
/Users/yourname
> pwd
Path
----
C:\Users\yourname
Do More
- Type
pwd20 times, saying "print working directory" each time to build muscle memory. - Write down the path that this command gives you. Find that same location using your computer's graphical file browser (Finder on Mac, Explorer on Windows).
6. What's Your Computer's Name? (hostname)
Do This
The hostname command displays the network name of your computer.
$ hostname
Zeds-MacBook-Pro.local
> hostname
zed-PC
Do More
- Just like with
pwd, type this command repeatedly to commit it to memory.
7. Make A Directory (mkdir)
Do This
The mkdir command is used to "make directories" (or folders). You can create a single directory or a nested series of them.
# Create a single directory
$ mkdir temp
# Create a directory inside another
$ mkdir temp/stuff
# Create a nested path of directories all at once
# Note: On Windows, mkdir may create nested paths by default
$ mkdir -p temp/stuff/things/deep-folder
You Learned This
You created new folders using `mkdir`. When you create a nested structure like `temp/stuff/things`, this is called a "path." It's a set of directions for the computer telling it where to find or create something in the folder tree on your hard disk. The `-p` flag tells `mkdir` to create parent directories as needed.
Do More
- Create 20 other directories at various levels inside your
tempdirectory. - Use your graphical file browser to look at the directories you just created.
- To create a directory with spaces in its name, wrap the name in quotes:
mkdir "I Have Fun"
8. Change Directory (cd)
Do This
The cd command lets you "change directory" and move around your file system.
# Move into the 'temp' directory
$ cd temp
# Check where you are
$ pwd
/Users/yourname/temp
# Move into a deeper directory
$ cd stuff/things
# Move up one level
$ cd ..
# Move up multiple levels
$ cd ../..
# Go back to your home directory
# On macOS/Linux '~' is a shortcut for home
$ cd ~
# On all systems, just 'cd' with no arguments works too
$ cd
You Learned This
You used `cd` to navigate through the directories you created. The special directory `..` always refers to the parent directory (one level up). This is a fundamental skill for connecting what you do in the command line with what you see in your graphical file browser.
Do More
- Navigate back to your home directory, then change into a deep directory (e.g.,
temp/stuff/things/deep-folder) with a singlecdcommand. - From that deep directory, get back to the
tempdirectory with one command (e.g.,cd ../../..). - Use your graphical file browser to find your "Documents" folder, then use
cdto navigate to it in the terminal. Do the same for your "Downloads" folder. - Remember that you can use quotes for directories with spaces:
cd "My Documents".
9. List Directory (ls)
Do This
The ls command "lists" the contents of the current directory.
$ ls
stuff
iamcool.txt
neat.txt
In PowerShell, ls is an alias for Get-ChildItem. You can also use dir.
> ls
Directory: C:\Users\yourname\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 12/17/2021 9:03 AM stuff
-a---- 12/17/2021 9:03 AM 0 iamcool.txt
You Learned This
You can see the files and folders in your current location by using `ls`. It's a command you'll use constantly to orient yourself and see what's available to work with.
Do More
- macOS/Linux: Try the
ls -lRcommand while inside yourtempdirectory. The-lflag gives a "long" detailed listing, and-Rlists the contents of all subdirectories recursively. - Windows: Do the same thing with
dir -R. - Use
cdto get to other directories on your computer (like Desktop or Documents) and then uselsto see what's in them.
10. Remove Directory (rmdir)
Do This
The rmdir command "removes directories." Importantly, it can only remove empty directories.
# Let's say we have an empty directory called 'old-project'
$ ls
old-project
# Remove it
$ rmdir old-project
# If you try to remove a directory with files in it...
$ rmdir stuff
rmdir: stuff: Directory not empty
You Learned This
To remove a directory, you use `rmdir`. If the command fails, it's almost always because the directory isn't empty. You'll learn how to remove directories that contain files in a later chapter.
Do More
- Make 20 more directories and then remove them all one by one.
- Make a single path of directories that is 10 levels deep, then navigate back up, removing them one at a time.
11. Moving Around (pushd, popd)
Do This
pushd and popd are powerful commands for quickly jumping between two directories. Think of it like a temporary bookmark.
# You're in your home directory. Create a deep path.
$ mkdir -p projects/website/css
$ pwd
/Users/yourname
# 'Push' into the new directory. This saves your current location and jumps.
$ pushd projects/website/css
~/projects/website/css ~/
# Now you are in the css directory.
$ pwd
/Users/yourname/projects/website/css
# 'Pop' back to where you were before.
$ popd
~
# And you're back home.
$ pwd
/Users/yourname
You Learned This
pushd saves your current location and moves you to a new one. popd "pops" the last saved location off the list and takes you back there. It's an incredibly handy way to switch back and forth between two places without typing long paths repeatedly.
Do More
- Use
pushdandpopdto move around various directories on your computer. - Create your own directory structure and practice navigating it with these commands.
- Pay attention to the output of
pushd. It shows you the "stack" of saved directories.
12. Making Empty Files (touch)
Do This
You can quickly create a new, empty file without opening a text editor.
The touch command is used for this. Its main purpose is to update a file's timestamp, but it creates the file if it doesn't exist.
$ touch my-new-file.txt
$ ls
my-new-file.txt
The New-Item command is used in PowerShell.
> New-Item my-new-file.txt -type file
> ls
my-new-file.txt
Do More
- Create a new directory,
cdinto it, and then make an empty file inside it. - Now,
cdback up one level (cd ..) and try to usermdiron the directory you just created. You should get an error because the directory is not empty. This reinforces the rule from Chapter 10.
13. Copy A File (cp)
Do This
The cp command is used to "copy" files and directories.
# Copy a file to a new name in the same directory
$ cp my-file.txt my-file-backup.txt
# Create a directory
$ mkdir my-folder
# Copy a file into that directory
$ cp my-file.txt my-folder/
# Copy an entire directory and its contents
# The -r flag means 'recursive'
$ cp -r my-folder my-folder-backup
You Learned This
You can duplicate files and entire folders with `cp`. The `-r` (or `-Recurse` on PowerShell) flag is crucial for copying directories because it tells the command to copy everything inside, not just the folder itself.
Do More
- Use
cp -rto copy more directories that have files in them. - Copy a file from your working directory to your Desktop or home directory.
- Find the files you copied using your graphical file browser and open one in a text editor.
14. Moving A File (mv)
Do This
The mv command is used to "move" a file. It's also used to rename a file.
# Rename a file
$ mv old-name.txt new-name.txt
# Create a directory
$ mkdir another-folder
# Move a file into that directory
$ mv new-name.txt another-folder/
You Learned This
Moving and renaming are the same operation with `mv`. If the destination is a new filename in the same directory, it renames. If the destination is a different directory, it moves the file.
Do More
- Move a file into a new directory, then move it back out to the original directory.
15. View A File (less, more)
Do This
When you want to look inside a file without editing it, you can use a "pager" program. These let you view the content one screen at a time.
less is a powerful pager. Use arrow keys to scroll and press q to quit.
$ less my-long-document.txt
more serves a similar purpose. Press spacebar to advance and q to quit.
> more my-long-document.txt
You Learned This
Pagers like `less` and `more` are essential for quickly inspecting the contents of files, especially log files or long documents, directly in your terminal.
Do More
- Open a plain text editor (like TextEdit on Mac or Notepad on Windows) and create a file with a few lines of text.
- Copy and paste the text repeatedly so the file is about 50-100 lines long. Save it.
- Use
lessormoreto view the file. Practice paging through it. - Use a pager to look at some of the empty files you created earlier. What do you see?
16. Stream A File (cat)
Do This
The cat command (short for "concatenate") reads a file and prints its entire content to the screen at once. It doesn't pause or page.
$ cat my-short-poem.txt
I am a fun guy.
Don't you know why?
Because I make poems,
that make babies cry.
You can also use it to combine multiple files.
$ cat file1.txt file2.txt
> cat file1.txt,file2.txt
You Learned This
Unlike `less` or `more`, `cat` just dumps the whole file to your terminal. This makes it ideal for viewing short files or for use with other commands, as you'll see in the next section.
Do More
- Make a few more short text files and view them with
cat. - Try the command to concatenate two files. What happens?
17. Removing A File (rm)
Do This
The rm command is used to "remove" files.
# Remove a single file
$ rm file-to-delete.txt
# Remove multiple files at once
$ rm file1.txt file2.txt file3.txt
To remove a directory that contains files, you must use the `-r` (recursive) flag. This is the command that solves the problem from the `rmdir` chapter. Be very careful with this command.
# Recursively and forcefully remove a directory and all its contents
$ rm -rf project-to-delete/
You Learned This
You used `rm` to delete files. To remove a directory and everything inside it, you combine `rm` with the `-r` flag. This is a powerful and destructive command, so always double-check what you are deleting.
Do More
- Clean up your
tempdirectory by removing all the files and folders from the exercises so far. - Write in your notebook: "Be careful when running
rm -r".
18. Pipes And Redirection
Do This
This is where the command line gets really powerful. You can chain commands together, sending the output of one command to be the input of another.
The Pipe `|`: Takes the output from the command on the left and "pipes" it to the command on the right.
# List all files, then pipe that list to 'less' to page through it
$ ls -l | less
Output Redirection `>`: Takes the output of the command on the left and writes it to the file on the right. This will overwrite the file if it already exists.
# Get a list of all files and save that list to a file called file_list.txt
$ ls > file_list.txt
Append Redirection `>>`: Takes the output of the command on the left and appends it to the end of the file on the right. It does not overwrite.
# Add a second directory's contents to our list
$ ls ../another-directory >> file_list.txt
Input Redirection `<` (Less common in daily use): Takes the content from the file on the right and uses it as input for the program on the left.
# Sort the contents of a file
$ sort < file_list.txt
You Learned This
Pipes and redirection are the building blocks of complex command line operations. By combining simple tools, you can accomplish very sophisticated tasks without writing a single line of code.
19. Wildcard Matching
Do This
The asterisk `*` is a "wildcard" that means "match anything." This allows you to perform actions on a group of files at once.
# List all files that end with .txt
$ ls *.txt
# List all files that start with 'photo'
$ ls photo*
# Remove all files that end in .tmp
$ rm *.tmp
You Learned This
Wildcards are a powerful way to work with multiple files that share a common pattern in their names. You can use `*` to match any number of any characters.
20. Finding Files (find)
Do This
When you need to find a file somewhere on your system, these commands are your best friend.
The find command is extremely powerful. The basic syntax is `find [where to start] -name "[what to look for]" -print`.
# Find all files named "report.docx" starting from the current directory (.)
$ find . -name "report.docx" -print
# Find all .png files inside your Documents folder
$ find ~/Documents -name "*.png" -print
You can use Get-ChildItem (or its alias ls or dir) with the `-Recurse` and `-Filter` flags.
# Find all .txt files starting from the current directory
> Get-ChildItem -Recurse -Filter "*.txt"
Do More
- Try starting your search from a different directory instead of
.(the current directory). - Try to find all the video files (e.g.,
*.movor*.mp4) on your computer, starting from your home directory. - Use output redirection (
>) to save that list of video files to a new text file calledmy_videos.txt.
21. Looking Inside Files (grep)
Do This
The grep command (an acronym for "global regular expression print") searches for a specific string of text inside files. It is one of the most useful command line utilities.
# Search for the word "error" in all .log files
$ grep "error" *.log
# Search for a phrase, ignoring case (-i)
$ grep -i "access denied" security.log
# Search recursively (-r) through a whole directory for a term
$ grep -r "API_KEY" .
PowerShell's equivalent is Select-String.
# Search for the word "error" in all .log files
> Select-String -Path *.log -Pattern "error"
You Learned This
Instead of manually opening files to find information, you can use `grep` or `Select-String` to instantly search through hundreds or thousands of files for the exact text you need.
Do More
- Try searching for a whole phrase by putting it in quotes, like
grep "new file" *.txt. - macOS/Linux: Try the
-ioption withgrepto make your search case-insensitive. - Take the list of video files you created in the last chapter and use
grepto find all the videos with a certain word in the title.
22. Getting Command Help (man)
Do This
When you forget how a command works or what options it has, you can access the built-in manual.
The man command (for "manual") shows you the official documentation for a command.
$ man ls
$ man grep
The help command provides detailed information.
> help Get-ChildItem
> help Select-String
You Learned This
You don't need to memorize everything. The `man` and `help` commands are your gateway to understanding every detail about the tools available to you. When in doubt, check the manual.
Do More
- Use
manorhelpto look up every one of the commands from your memorization list. Skim through their options.
23. Finding Help (apropos)
Do This
Sometimes you know what you want to do, but you don't know the name of the command.
apropos searches the manual page descriptions for a keyword.
# I want to do something with a 'directory'
$ apropos directory
help with a wildcard can find related commands.
# What commands are related to 'file'?
> help *file*
You Learned This
When you're stuck, these commands can help you discover the right tool for the job by searching for keywords related to the task you want to accomplish.
24. Working with Your Environment
Do This
Your shell has "environment variables" that store information about your session, like your username, home directory, and command search path.
# Print all environment variables
$ env
# Print the value of a specific variable (note the $)
$ echo $USER
zed
$ echo $HOME
/Users/zed
# Create a new temporary variable
$ export MY_VARIABLE="Hello World"
$ echo $MY_VARIABLE
Hello World
# Unset the variable
$ unset MY_VARIABLE
# List all environment variables
> Get-ChildItem Env:
# Print the value of a specific variable
> $env:USERNAME
zed
> $env:OS
Windows_NT
# Create a new temporary variable
> $env:MY_VARIABLE = "Hello World"
> $env:MY_VARIABLE
Hello World
# Remove the variable
> Remove-Item Env:\MY_VARIABLE
You Learned This
Environment variables control how your shell and other programs behave. You can create, modify, and remove them to configure your tools.
Do More
- List out all the environment variables on your system and go online to look up what a few of them do (e.g.,
PATH,USER,HOME). - Challenge: Go online and research how to permanently change your
PATHvariable for your specific operating system. This is a common task when installing new development tools.
25. Exiting Your Terminal (exit)
Do This
The final command is the simplest: how to close your terminal session.
$ exit
Next Steps
Go Forth
You have completed the crash course! From now on, you shouldn't be afraid of using the command line. If you are aspiring to be a programmer, it is the best first step to understanding how a computer is a "language machine."
My advice for getting good at the CLI is to force yourself to use it every day, no matter how painful it seems. The advantage of a graphical interface (GUI) is that you get visual cues to remind you how to use a tool. With the CLI, you have to recall every command from memory, which is irritating at first. A great trick is to create your own personal cheat sheet. When you learn a new command you know you'll need again, write it down. Soon, you won't need the cheat sheet anymore.
Commands for Further Research
To continue your learning, use the man or help command to look up what these more advanced tools do.
macOS / Linux:
xargssudochmodchown
Windows (PowerShell):
forfilesrunasattribicacls