Intro to the Command Line

teaching-materials.org/cli

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important
  • Help each other
  • Have fun

Welcome!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of the class?
  • What's your favorite ice cream flavor?

Agenda

This class will be a combo of lecture + exercises
  • Command line "lingo"
  • Working with folder directories
  • Working with files
  • Standard input/output
  • Working with commands
  • File permissions
  • Running and stopping processes
  • Real world examples

The "lingo"

  • "Terminal"
  • "Command-line"
  • "Command prompt"
  • "Shell"
  • "Console"


These are all pretty much the same thing.

What is a Terminal?


A text-based command interpreter.


The most common shell is "bash".


For Mac OS or Linux, use the "Terminal" application.


For Windows, use Git Bash.
(Download here if you haven't installed yet.)

Prompt

Command Line prompt

Prompt


Usually shows your username and computer name.


Indicates that the terminal is ready for a command.

Cursor

Command Line cursor

Cursor


Indicates your current spot in the terminal.


Shows you where the stuff you type will go.

Your First Command


  1. Type echo hello into your terminal.
  2. Press the enter key.

The Current Directory

pwd

(Print Working Directory)


Type it whenever you want to see what directory (folder) you’re in.

pwd

(Print Working Directory)

Your first command, pwd

clear


The clear command clears the contents of the terminal and issues a prompt.


This is good for removing previous output that is unnecessary to the task at hand.


Feel free to use this whenever things get too cluttered.

Directories


Also referred to as "folders".


A container for files or other directories.


Nested files and directories can be referenced using paths.

Directory Trees


The set of all folders, taken together, makes up your entire file system.


This system is organized into a kind of upside down tree.

Directory Tress

At the very top of the tree is the root folder.


Unix file directory system

Paths


Each directory or file is separated by a forward slash "/"


There are two kinds of paths:


  • Relative: Desktop/the_project/overview.txt
  • Absolute: /Users/jane/Desktop/logo.png

cd


The cd command changes the current working directory.


It expects a file path as an "argument".


If no file path is given, it assumes your home directory by default.

cd

Command line cd

Shortcuts


  • Current Directory: .
  • Parent Directory: ..
  • Home Directory: ~
  • Previous Directory: -


Bonus: Drag a folder into the terminal to show its path.

(Doesn't quite work in Windows.)

ls


The ls command lists the contents of a directory.


It expects a file path as an "argument".


If no file path is given, it assumes the current directory by default.

ls

Command line ls

Flags


The ls command accepts several option flags.


A flag is a special argument that is used to set an option for the command.


These are commonly a hyphen followed by a single character (e.g. -g)


Setting the -l flag on the ls command causes it to provide more verbose (long) output.

ls -l

Command line ls with flags

Hidden Files


Filenames that begin with a period are hidden from normal output.


e.g. ".bashrc"


Use the ls command with the -a flag to see hidden files in addition to the usual output.


Type ls -la into your terminal.


Use the -h flag to get human readable file sizes.

ls -la

Command line hidden files using flag -la

Man Pages

man

The man command brings up the manual for the specified command. Use <space> or the arrow keys to page through and press q to exit.

$ man ls

Love the Tab

Tab completion autocompletes commands and filenames.

  • Pressing <tab> once autocompletes a unique instance.
  • Pressing <tab> twice gives you all the options available.
$ cd P

cd & ls


Play with the cd and ls commands.


Be sure to incorporate:

  • relative file path
  • absolute file path
  • the . shortcut
  • the .. shortcut
  • the ~ shortcut
  • cd without an argument


Use pwd to check your location periodically.

Open


Use the open command to open a file or directory in its default app.


Pass the path of the file or directory name as the argument.


It does the equivalent of double-clicking the item.


(Sadly, this does not work in Windows. 😞)

Making a Directory


Use the mkdir command to create a new empty directory.


Pass the path of the directory name as the first argument.


If the base of the path doesn't already exist, the command will fail.


Use the -p flag to create the full path if non-existent.

mkdir

Command line make directory

Removing Directories


Use the rmdir command to remove an empty directory.


Use rm -r to remove a non-empty directory.

rmdir

Command line remove directory

Let's Develop It!


  1. cd to your home directory.
  2. Create the girl/develop directory path.
  3. Navigate into the girl/develop directory.
  4. Create the it directory.
  5. Navigate up two directories.
  6. Use the pwd command to verify you are home.
  7. Remove the girl/develop/it path.

Let's Develop It

Exercise 1 answer

Files


Use cat to output the contents of a file to the console.


Use more to step through the contents of a file one screen at a time.


Use less to step backwards or forwards.

Let's Develop It!


Explore the /usr/share/misc files using cat, more, and less


Can you find your birth month's stone and flower in the birthtoken file?


Sorry, Windows users - I haven't found a good file sample for this yet!
Try looking over the shoulder of a neighbor.

Let's Develop It!

Exercise 2 answer

Create a File

touch

Use the touch command to create a new file.


The touch command expects the name of your new file as an argument.

touch

(create a file)

touch

Copy a File

cp

Use the cp command to copy a file.


The cp command takes two arguments:

1st argument = the "origin" file

2nd argument = the "destination" file

$ cp resume.txt resume-copy.txt

cp

(copy a file)

$ cp origin destination
cp

Copy a Directory

cp -R

Use the cp -R command to copy a directory.


The cp -R command takes two arguments:

1st argument = the "origin" directory

2nd argument = the "destination" directory

$ cp -R homework old-homework

cp -R

(copy a directory)

$ cp -R origin destination
cp-R

Moving (or renaming) a File/Directory

Use the mv command to move a file or directory.


The mv command takes two arguments:

1st argument = the "origin"

2nd argument = the "destination"

Move a File/Directory

mv origin destination

move file/directory

Rename a File/Directory

mv orig dest

rename file/directory

Remove a File

rm

Use the rm command to remove a file.


Expects the name of the file you are removing as an argument.

rm

(remove a file)

remove a file

Let's Develop It!

  1. Create a folder called cli
  2. Make that folder your current working directory
  3. Create two files: file1.txt, file2.txt
  4. Copy file1.txt and call the copy file3.txt
  5. Create a directory called folder1
  6. Move file1.txt into folder1
  7. List the contents of folder1 without going into it
  8. Rename file1.txt to myfile.txt
  9. Remove the directory folder1, without deleting myfile.txt first
  10. Clear your terminal

Edit a File

You can use various editors built into bash:

$ vi myfile.txt

$ emacs myfile.txt

$ pico myfile.txt


Or on a Mac, you can open with any desktop app:

$ open -a TextEdit myfile.txt

Or with the default editor:

$ open -t myfile.txt

Search within a File

grep

Use the grep command to search in files.


The grep command outputs only the lines in a file that match a given pattern.


The 1st argument is the pattern to match, and the 2nd, 3rd, and so on are the files to search within.

$ grep pattern file

grep

(search within a file for text that matches a pattern)

grep

Wildcard Matching

Use the * (asterisk) symbol to match anything.


You can use this to search through all of a particular file type.

$ grep hello *.txt

The shell will build a list of all the files that match the non-asterisk part.

Finding Files

find

Use the find command to find files according to name/metadata.


Find all txt files under the current directory:

find . -name '*.txt' -print

find

(finding files)

find

Standard Output


Most commands display their results to a mechanism called the standard output.


By default, this directs its content to the display.


The standard output can be redirected to a file using the > operator.


ls > file_list.txt

Standard Output


In order to append to the file instead of overwriting it, use the >> operator instead.


ls >> file_list.txt


Both the > and >> operator will create the file if it doesn't exist.

Standard Input


Whenever commands accept keyboard input, it's likely they are really just drawing input from a mechanism called standard input.


By default, this is set to keyboard input.

Standard Input


The input to a command can be redirected to a file by using the < operator.


sort < file_list.txt


Both input and output can be redirected at the same time.


sort < file_list.txt > sorted_file_list.txt

Let's develop it!

  1. In the cli directory, output the contents of file2.txt to the terminal
  2. Add a sentence to file2.txt
  3. Add a few more sentences to file2.txt
  4. Search the file for the word of your choice and add the results to file3.txt

Filters


Filters are commands whose behavior follows the following pattern:

  1. Accept input from standard input.
  2. Perform some operation on it.
  3. Send the results to standard output.

Filters

Check out the man pages for the following:


sort

uniq

grep

head

tail

fmt

pr

tr

sed

awk

Pipes


The "|" character can be used to allow commands to communicate during execution.


Pipes are placed between commands.


A pipe will cause the output of the left command to be used as the input of the right command.


ls -l | grep "myfile.txt" du | sort -nr

Let's Develop It!


Use the ls and grep commands to print out only the files in your home directory that contain the word "bash".

Let's Develop It!


ls -a | grep bash

Exercise 4 Example

Command Line Movement

  • ctrl-a: jump to beginning of line
  • ctrl-e: jump to end of line
  • alt-f: jump forward a word
  • alt-b: jump back a word
  • alt-d: delete word
  • alt-t: transpose two words
  • ctrl-xx: jump back to your last edit, again to get back to original position

More Command Line Movement

  • The left/right arrow keys let you edit within a command
  • The up/down arrow keys let you select previous commands
  • tab auto-completes filenames


Bonus for Macs: Hold the option key and click to move the cursor.

Command Line History

Use the history command to see a list of all your previous commands.


Each command will be listed next to a line number.


A few history-related commands:

  • !!: Latest command
  • !568: Command by line #
  • !open: Command matching string

history

history

Let's Develop It!


  1. Use your up and down arrows to locate a past command with one or more arguments.
  2. Move your cursor to the beginning of the line.
  3. Move your cursor to the end of the line.
  4. Change one of the arguments and run it.
  5. Run the date command.
  6. Re-run the command from step 4 using !.
  7. Time the execution of your original command by running time !!.

Mac/Linux-Only Zone


The following sections rely on the Unix system and will not work in a bash emulator on a Windows PC.


You can work with a partner, or try the commands on Cloud9, and online workspace.

Permissions


The unix security model breaks up file permissions into three groups:


  1. Owner
  2. Group
  3. Others


rwx

r-x

r-x

owner group others

Remember ls -l?

Command line ls with flags

Changing Permissions


Use chmod to change permissions on a file/directory


The argument has three sections:

  1. u, g, o to signify which level to target.
  2. + or - to indicate whether adding or removing.
  3. r, w, x to indicate what type of permission to change.

Changing Permissions


Use chmod to change permissions on a file/directory


Examples:

chmod u+w to add write permissions for the file's owner.

chmod go-rwx to remove all permissions for the file's group and everyone else.


Windows permissions work differently. You can view them with ls -l, but you can't change them with chmod

Let's Develop It!


  1. Create a new file named testfile in your home directory.
  2. Grant yourself execute permission on the file.
  3. Remove read permission on testfile from your group and everyone else.
  4. Delete testfile.

Let's Develop It!

Exercise 3 Example

Processes


Whenever a command is executed, a new process is created.

top


The top command provides an up-to-date feed of information on the most active processes across the machine.


Useful for finding processes that are hogging the CPU.

ps


The ps utility displays all of your processes that have controlling terminals.

ps

Command Line ps Processes

Key Sequences


Ctrl + Z: Suspend the current process


Ctrl + C: Terminate the current process

Suspending a Process

Command Line suspending a process

bg & fg


The bg and fg commands bring a suspended process back into a running state.


bg runs it in a background process.

fg runs it in the foreground of the current terminal.


By default they target the most recently suspended process.

The job number can be provided as an argument. (The number we saw when we suspended the process)

Let's Develop It!


  1. Run the top command.
  2. Suspend the process.
  3. Bring the process back into the foreground.

Let's Develop It!

Exercise 5 Example

kill


The kill command terminates or sends a signal to a process.


It takes the process id (PID) as an argument.


You can find the PID using top or ps.

Let's Develop It!


  1. Clear your terminal and run the yes command.
  2. Use the Ctrl+Z key sequence to suspend the process.
  3. Use the bg command to send the process to the background.
  4. Notice the output is still happening even though the process is running in the background.
  5. Open a new terminal window, locate the PID for the "yes" process and use it to kill the process.

Real World Examples


Here are some examples of using the command line to accomplish tasks relating to development.

Serve up a Directory


python -m simpleHTTPServer


Don't forget: you can Ctrl + C to exit.

Version Control


Check out Try Git for an easy intro, or watch for our next GDI Git workshop.

Watching a Log File


tail -f /var/log/wifi.log

Where's the prompt?!


Different processes have different ways of exiting back to the prompt. If you're stuck, try one of these:


  • ctrl + c
  • ctrl + x
  • q
  • :q
  • esc key, then :q

Just for Fun!


cal


say hello

More Resources