Command Line Interface

Basics

The command line interface is a means of interacting with a computer using written commands. This method of interacting with a computer is a stark contrast to the graphical user interface of today’s modern, hyper-intuitive computers. GUI is much more widely used, but savvy users (especially tech professionals) may prefer CLI for efficiency and speed.

Ryans-MacBook-Pro:~ ryanwingate$

Command Line Programs by Operating System

OS Program To Open…
Mac Terminal Press CMD + Space, type Terminal, press return
Windows Command Prompt Press Win + R keys
Linux Terminal press Ctrl + Alt + T keys
Ryans-MacBook-Pro:~ ryanwingate$ date
Sat Mar 10 06:28:00 PST 2018

Terminal vs Shell vs Console

  • Shell - a program that actually processes commands and returns output. Mac and Linux today run the bash shell by default.
  • Terminal - a wrapper program that runs a shell. The name is from computer terminal, a physical device with monitor and keyboard.
  • Console - a special sort of terminal originally used to interface with the operating system at a low level. The distinction between a console and a terminal is somewhat lost to history, and today the terms are used more or less interchangeably.

Essential Concepts

  • View Command History by pressing up and down arrows.
  • Alternatively, use command history.
  • Use tab completion by typing the first few letters of a filename and then pressing Tab.
  • Use man followed by the name of a command to read the manual pages associated with that command. Press Q to exit the manual page.
Ryans-MacBook-Pro:~ ryanwingate$ man man
man(1)                                                                  man(1)

NAME
       man - format and display the on-line manual pages

SYNOPSIS
       man  [-acdfFhkKtwW]  [--path]  [-m system] [-p string] [-C config_file]
       [-M pathlist] [-P pager] [-B browser] [-H htmlpager] [-S  section_list]
       [section] name ...

DESCRIPTION
       man formats and displays the on-line manual pages.  If you specify sec-
       tion, man only looks in that section of the manual.  name  is  normally
  • Send an “interrupt signal” to a program that has taken over the terminal (like ping) by typing Ctrl-C.
Ryans-MacBook-Pro:~ ryanwingate$ ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: icmp_seq=0 ttl=58 time=22.318 ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=58 time=21.701 ms
^C
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 21.701/22.010/22.318/0.308 ms
Ryans-MacBook-Pro:~ ryanwingate$
  • Some (‘line-based’) programs take input from standard input (stdin) and write to standard output (stdout). To interrupt these, type Ctrl-D to send an ‘End of File’ character.
Ryans-MacBook-Pro:~ ryanwingate$ sort
beta
gamma
alpha
alpha
beta
gamma
Ryans-MacBook-Pro:~ ryanwingate$

Ctrl-D was pressed after entering ‘beta’, ‘gamma’, ‘alpha’ to prompt sort to execute.

  • In addition to ‘line-based’ programs, there are also ‘full-screen’ programs.
  • less is a full-screen terminal program used to view text files. The man command actually uses the less program to print the manual pages to screen.
LESS(1)                                                                LESS(1)

NAME
       less - opposite of more

SYNOPSIS
       less -?
       less --help
       less -V
       less --version
       less [-[+]aABcCdeEfFgGiIJKLmMnNqQrRsSuUVwWX~]
            [-b space] [-h lines] [-j line] [-k keyfile]
            [-{oO} logfile] [-p pattern] [-P prompt] [-t tag]
            [-T tagsfile] [-x tab,...] [-y lines] [-[z] lines]
            [-# shift] [+[+]cmd] [--] [filename]...
       (See  the  OPTIONS section for alternate option syntax with long option
       names.)

DESCRIPTION
       Less is a program similar to more (1), but which allows backward  move-
       ment in the file as well as forward movement.  Also, less does not have
       to read the entire input file before  starting,  so  with  large  input
       files  it  starts  up  faster than text editors like vi (1).
  • In addition to terminal-based full-screen text file viewers, several text file editors are available as well. Among these are: vim, emacs, joe and many others.
  • One in particular is nano, which takes the text file to edit as a parameter.
Ryans-MacBook-Pro:~ ryanwingate$ nano somefile.txt
GNU nano 2.0.6             File: somefile.txt                                 

sometext in somefile.txt



                              [ Read 1 line ]
^G Get Help  ^O WriteOut  ^R Read File ^Y Prev Page ^K Cut Text  ^C Cur Pos
^X Exit      ^J Justify   ^W Where Is  ^V Next Page ^U UnCut Text^T To Spell

In nano:

  • To save or ‘WriteOut’ use Ctrl-O.
  • To exit, use Ctrl-X.

The Filesystem

A discussion of the command line is incomplete without some treatment of the filesystem itself.

A computer’s filesystem can be thought of as a tree structure, where the branches are like directories and leaves are like files. In this analogy, a user’s home directory would be the trunk of the tree. It is where a user begins when she first opens the command line. The tilde character indicates the user is in the home directory. On my computer, upon opening a terminal, this initial prompt looks like:

Ryans-MacBook-Pro:~ ryanwingate$

Two of the most basic commands command line users must familiarize themselves with are ls (“list directory contents”) and cd (“change directory”).

ls prints the contents of the current working directory. In the following case, I’ve executed ls from within my ‘website’ directory where I keep the files for ryanwingate.com.

Ryans-MacBook-Pro:website ryanwingate$ ls
404.html		_data_references	_site
CNAME			_drafts		        assets
Gemfile			_includes		in-progress.html
Gemfile.lock		_layouts		index.html

cd changes the directory the user is currently in. For example, from the previous location, I execute cd \_layouts, which changes the current working directory from the website directory to the _layouts directory.

Ryans-MacBook-Pro:website ryanwingate$ cd _layouts
Ryans-MacBook-Pro:_layouts ryanwingate$

Users can also specify command line ‘options’ to modify the way that command line commands execute. For example, a common modification to the list directory contents command is ls -la. From the manual pages:

The following options are available:

[email protected]      Display extended attribute keys and sizes in long (-l) output.

-1      (The numeric digit ''one''.)  Force output to be one entry per
        line.  This is the default when output is not to a terminal.

-A      List all entries except for . and ...  Always set for the super-
        user.

-a      Include directory entries whose names begin with a dot (.).

This raises the question of what directories and files begin with a dot (.) These types of files are usually called ‘dotfiles,’ and hidden by default when the system shows a directory listing, hence their other names: hidden folders or hidden directories. The typical usage for this type of file is to store user preferences or preserve the state of some application.

There are also two special hidden directories in every directory, called . and ... . refers to the current working directory. As a result, the command cd . does precisely nothing. .. refers to its parent directory (IE, the directory that contains the current working directory). If you are navigating the file system using relative paths, cd .. will take you “back,” or “up” (depending on whether you prefer to conceptualize the file tree as growing forward or downward).

Now, what is a relative path? It is a path to one directory from another. An example: ./website/ defines the location of the website directory relative to ., or, the current working directory. The . is commonly omitted.

Absolute paths, on the other hand, are a path from the root directory. The CD command accepts either relative or absolute paths. For example, the files for this website live at the following file location on my MacBook:

/Users/ryanwingate/Library/Mobile Documents/com~apple~CloudDocs/The Grind/website

I access this directory very routinely, so how do I avoid navigating to it using relative links, or typing that long absolute URL every day? By defining an “Alias” that lives in the root directory, and which executes cd /Users/ryanwingate/Library/Mobile Documents/com~apple~CloudDocs/The Grind/website every time I type it. How?

Defining an Alias

  1. cd. This takes you home.
  2. ls -la. This should show you a file called ‘.bash_profile’
  3. nano .bash_profile. This will open the .bash_profile file in nano, the text editor discussed previously.
  4. Add alias web='cd ~/Library/Mobile\ Documents/com~apple~CloudDocs/The\ Grind/website', where ‘web’ and the long path that follows the cd command are replaced with your own alias and absolute url.
  5. “Write-out” the change, and restart the terminal. Now typing the alias is no different than typing that long cd command:
Ryans-MacBook-Pro:~ ryanwingate$ web
Ryans-MacBook-Pro:website ryanwingate$

Basic Commands

Command Function
clear Clears the console window
history Prints several recently used commands
ls Lists the contents of the current directory
unzip Unzips a zipped directory listed as arguments
cat Prints the contents of the files listed as arguments
wc Prints the number of lines, words, and bytes in a file
diff Compares files and shows you how they differ

Commands I Use Frequently

Command Function
python Starts the Python interpreter (if installed)
ipython Starts the iPython interpreter (if installed)
bundle exec jekyll serve Spins up a web server on the local machine to host the jekyll website in the current working directory
git add . Stages the modified files in the current working directory (and subdirectories) within a git repository for commit
git commit -m “Some message” Commits the staged files to the git repository
git push origin master ‘Pushes’ the git repository and associated files to the github server


Content for this note is taken from information I learned while pursuing the Udacity Data Analyst Nanodegree. Udacity is an online tech education service that offers both free and paid, tech-focused training. Learn more.