Command Line
Command Line
1
Organization of a computer system
users applications
graphical user
shell
interface (GUI)
operating system
hardware
(or software acting like hardware: “virtual machine”)
2
Organization of a computer system
graphical user
shell
interface (GUI)
system
calls
operating system
hardware
(or software acting like hardware: “virtual machine”)
3
Organization of a computer system
Easier to program users applications
with and automate;
Not so convenient to
use (maybe) typed commands
graphical user
shell
interface (GUI)
system
calls
operating system
hardware
(or software acting like hardware: “virtual machine”)
4
Organization of a computer system
users applications
this
class
graphical user
shell
interface (GUI)
operating system
hardware
(or software acting like hardware: “virtual machine”)
5
What is a Command Line Interface?
• Interface: Means it is a way to interact with the Operating System.
6
What is a Command Line Interface?
• Interface: Means it is a way to interact with the Operating System.
• Command Line: Means you interact with it through typing commands
at the keyboard.
7
What is a Command Line Interface?
• Interface: Means it is a way to interact with the Operating System.
• Command Line: Means you interact with it through typing commands
at the keyboard.
So a Command Line Interface (or a shell) is a program that lets you
interact with the Operating System via the keyboard.
8
Why Use a Command Line Interface?
A. In the old days, there was no choice
9
Why Use a Command Line Interface?
A. In the old days, there was no choice
a. No commercial computer had a GUI until Apple released the Lisa in 1983 (at
$10, 000!!!)
10
Why Use a Command Line Interface?
A. In the old days, there was no choice
a. No commercial computer had a GUI until Apple released the Lisa in 1983 (at
$10, 000!!!)
b. There might still be no choice if you are interacting with a computer via a
non-graphical terminal.
11
Why Use a Command Line Interface?
A. In the old days, there was no choice
a. No commercial computer had a GUI until Apple released the Lisa in 1983 (at
$10, 000!!!)
b. There might still be no choice if you are interacting with a computer via a
non-graphical terminal.
B. Many tasks are faster than in a GUI
a. Suppose you wanted to see all the files in a directory that had the word
“lecture” in their name.
12
Why Use a Command Line Interface?
A. In the old days, there was no choice
a. No commercial computer had a GUI until Apple released the Lisa in 1993 (at
$10, 000!!!)
b. There might still be no choice if you are interacting with a computer via a
non-graphical terminal.
B. Many tasks are faster than in a GUI
a. Suppose you wanted to see all the files in a directory that had the word
“lecture” in their name.
C. Most shells let you write scripts (programs) to automate complex tasks
which you could not do with a GUI
13
Three Different “Shells”
There are (and have been) 100’s (maybe thousands) of shells. We will
briefly mention 3 of them still in use:
1. Command Prompt
2. Windows Powershell
3. Bash
14
Command Prompt
All versions of Windows have included a Command Prompt program.
It acts like a MSDOS interface to the computer.
15
Windows Powershell
Windows Powershell was an improved shell for Windows first released in
2006. The latest version came out in 2016.
16
Bash and UNIX
In this class we will be learning a little bit about the Bash shell, which is
currently the most popular shell used on the UNIX family of systems.
This is NOT a UNIX class, and we will not go into UNIX in any depth, but
we will talk about Bash and some common UNIX commands.
17
What is Unix?
• Linux:
– a “Unix-like” operating system
• Whether an OS is Unix or “Unix-like” is mostly about whether the OS has a tiny bit of original
Unix code and/or the activity of lawyers
How Do I Get Access to Bash?
If you’re using a MAC, then you have it. Just open up a terminal window.
That is a Bash shell.
19
How Do I Get Access to Bash?
If you have a Windows Machine you have the 3 options given in the
Introduction Lecture.
20
How Do I Get Access to Bash?
If you have a Windows Machine you have the 3 options given in the
Introduction Lecture.
1. For Windows 10, you can use the Windows Subsystem for Linux
a. This might be the future of “running UNIX” on Windows systems
b. This won’t work if you’re using something earlier than Windows 10
c. Also this may take a little more work to configure
21
How Do I Get Access to Bash?
If you have a Windows Machine you have the 3 options given in the
Introduction Lecture.
1. For Windows 10, you can use the Windows Subsystem for Linux
a. This might be the future of “running UNIX” on Windows systems
b. This won’t work if you’re using something earlier than Windows 10
c. This also might take a little more work to configure
2. You can download and run Cygwin
a. This should work on all Windows systems later than XP
22
How Do I Get Access to Bash?
If you have a Windows Machine you have the 3 options given in the
Introduction Lecture.
1. For Windows 10, you can use the Windows Subsystem for Linux
a. This might be the future of “running UNIX” on Windows systems
b. This won’t work if you’re using something earlier than Windows 10
c. This also might take a little more work to configure
2. You can download and run Cygwin
a. This should work on all Windows systems later than XP
3. You can connect to the cs dept computer lectura using a terminal
a. This requires the least resources on your computer
b. You must be connected to the Internet, lectura can get slow, files not local, etc
23
Unix Commands
• Syntax:
command options arguments
24
Executing commands
• Typing a command name at the bash prompt and pressing the ENTER key causes
the command to be executed.
• The command's output, if any, is displayed on the screen. Examples:
% hostname
lectura.cs.arizona.edu
% whoami
eanson
% true
% date
Sat Aug 15 18:54:39 MST 2015
% ps
PID TTY TIME CMD
22758 pts/18 00:00:00 bash
30245 pts/18 00:00:00 ps
25
Command-line arguments
% factor 223092870
223092870: 2 3 5 7 11 13 17 19 23
26
Command-line options
• Many commands accept options that adjust the behavior of the command.
• Options almost always begin with a '-' (minus sign). Options are usually specified immediately
following the command. For most programs the ordering of options is not significant but that is a
convention, not a rule.
• Examples:
% date
Thu Jan 13 02:19:20 MST 2005
% date -u
Thu Jan 13 09:19:22 UTC 2005
% wc Hello.java
5 14 127 Hello.java
% wc -l -w Hello.java
5 14 Hello.java
• The command wc -l -w Hello.java has two options and one operand (the file Hello.java).
27
Options, continued
% date-u
% wc -l-w Hello.java
% wc -- notes Hello.java
28
Finding out about commands (continued)
29
Example: “man man”
30
Example: “man man”
31
Example: “man ls”
32
Finding commands
34
Referring to files: Absolute Paths
ee ff
gg
35
Referring to files: Absolute Paths
ee ff
36
The current directory
/
• Invariably you are in a particular
directory in the tree called the
current (working) directory
– commands are executed in this context
bb cc dd
37
The current directory
/
• Invariably you are in a particular
directory in the tree called the
current (working) directory
– commands are executed in this context
bb cc dd
38
Referring to files: Relative Paths
/
• A relative path specifies how to
get to a file starting from the
current directory bb cc dd
– ‘..’ means “move up one level”
– ‘.’ means current directory
– lists the directories along the ff
ee
path separated by “/”
gg
Example:
ff relative to ee is: ../ff
39
Referring to files: Relative Paths
/
• A relative path specifies how to
get to a file starting from the
current directory bb cc dd
– ‘..’ means “move up one level”
– ‘.’ means current directory
– lists the directories along the ff
ee
path separated by “/”
gg
Example:
cc relative to ee is: ?
40
Referring to files: Relative Paths
/
• A relative path specifies how to
get to a file starting from the
current directory bb cc dd
– ‘..’ means “move up one level”
– ‘.’ means current directory
– lists the directories along the ff
ee
path separated by “/”
gg
Example:
cc relative to ee is: ../../cc
41
Home directories
• When you log in, your current directory is your home directory
• Notational shorthand:
– absolute path to one’s own home directory: ~
– absolute path to some other user joe’s home directory: ~joe
42
Absolute versus relative?
43
Unix commands for dealing with files and directories
Examples:
44
Seeing What Files are in a Directory
45
Handy options for ls
• -t Sort by modification time instead of alphabetically.
• -h Show sizes with human-readable units like K, M, and G.
• -r Reverse the order of the sort.
• -S Sort by file size
• -d By default, when an argument is a directory, ls operates on
the entries contained in that directory. -d says to operate on the
directory itself. Try "ls -l . " and "ls -ld .".
• -R Recursively list all the subdirectories.
• There are many more and you might want to look at the man page
and play with them
More commands for dealing with files
• cp file1 file2
• copy file1 to file2
• mv file1 file2
• move file1 to file2
• rm file
• removes the file
• for directories use the option “-r”
• mkdir dir
• make a (sub) directory in the current directory
• vi [file]
• the vi editor
• vimtutor
• a tutorial for using vi
47
Three handy options for cp:
• wc [file]
• word count: counts characters, words, and lines in the input
• (already used as an example)
• cat [file1] [file2]…
• concatenates files and writes them to standard output
• head –n [file]
• show the first n lines of the input
• tail –n [file]
• show the last n lines of the input
• touch [file1] [file2]…
• updates the timestamp on files, creating them as needed
49
Getting more information about files
50
Getting more information about files…
(1)
access permissions
– normal file
file type d directory
l (ell) symbolic link
51
File access permissions
52
How does this relate to Windows and File Explorer
Directories are organized as trees and the GUI lets you navigate those
trees:
53
How does this relate to Windows and File Explorer
One difference in organization is that Windows has a tree per “drive”
instead of one root.
Notice it kind of looks like “Computer” is the root of the tree, but it
doesn’t show up in the command line.
54
How does this relate to Windows and File Explorer
You can’t change directories above the C: root. You can get to another
drive by using cd <drive letter>:
55
So What About Cygwin?
Cygwin sets up a root directory at the location where cygwin was
installed. But it mounts the drive root directories under:
/cygdrive
56
So What About Cygwin?
57
And What About Linux Subsystem for Windows?
• The location of the root directory is hidden in the Windows File System
– This is because files created by linux programs/commands in this area are not
compatible with Windows programs
58
Symbolic Links
Motivation:
Often you will want to reach a “distant” directory from your home directory. For example,
in the Linux Subsystem for Windows the files that can be modified by windows programs
are in the directory /mnt/<drive letter>. On my system I want to work with files here:
/mnt/c/Users/Eric/Documents/UofA/cs210/WorkArea
Using the following command will set up a symbolic link to my desired directory
% ln -s /mnt/c/Users/Eric/Documents/cs210/WorkArea/ cs210
59
Symbolic Links
Doing an ls after creating the link I see:
% ls
cs210
This can be treated like a directory. I can usd cd to enter it. However, if I do a
% ls -l
lrwxrwxrwx 1 eanson eanson 48 Aug 22 10:49 cs210 ->
/mnt/c/Users/Eric/Documents/cs210/WorkArea/
That lowercase "L" at the start of the line indicates that cs210 is a symbolic link, often
shortened to "symlink".
60
Symbolic Links
% ls cs210
simple.py
The cs210 symlink creates the illusion that my home directory has an cs210
subdirectory
~/352/a2 % ls /mnt/c/Users/Eric/Documents/cs210/WorkArea
simple.py
61
Symbolic Links
Key point:
Symbolic links are handled by the operating system.
Benefit:
A program doesn't have to do anything special to follow a symlink to its destination.
62
Symbolic Links
• A symlink is kind of like a "Windows shortcut done right.”
• Unix also has quite a different kind of link (hard) which we won’t say
anything more about (just be aware that you usually want symbolic).
Sidebar: Windows shortcuts
I've made a Windows shortcut named lf.txt
that references longFileName.txt.
• C:>type longFileName.txt
• Tue, Sep 01, 2015 5:50:25 PM
• C:>type lf.txt.lnk
• L▒F▒ ▒[▒▒ $_▒▒▒▒[▒▒]P▒O▒ ▒:i▒+00▒/C:\:1▒Bcygwin$▒▒<A"G▒cygwin41▒<L home
▒▒<▒"G▒home<1! ...
• If a Windows program wants to handle shortcuts, it's got to have special code to do it!
Symbolic Links
• File-related utility programs often have special handling for symbolic
links.
• One example is ls, whose -L option says to "follow" the link.
•% ls -l cs210
•lrwxrwxrwx 1 eanson eanson 48 Aug 22 10:49 cs210
-> /mnt/c/Users/Eric/Documents/cs210/WorkArea/
65
Input and output
• Other streams can be created using system calls (e.g., to read or write a
specific file)
66
I/O Redirection
67
Combining commands
Example:
“pipe”
v1: Get login names v2: Sort login names v3: Get unique login names
% who| cut -f1 -d " " % who|cut -f1 -d" "|sort % who|cut -f1 -d" "|sort|uniq
ken dmr dmr
dmr dmr francis
ken dmr ken
francis francis rob
rob ken walt24
walt24 ken wnj
dmr ken
rob rob v4: Get the count
wnj rob % who|cut -f1 -d" "|sort|uniq|
dmr walt24 wc -l
ken wnj 6
stdin and stdout and Python
Side note: You will want to be able to run Python from your command
line. MAC users should already be set.
If you're using Cygwin, you might want to install python3, and likewise if
you're using WSL (Windows Subsystem for Linux). Here is a link that
talks about installing Python (and other things) on WSL
https://blogs.windows.com/buildingapps/2016/07/22/fun-with-the-windo
ws-subsystem-for-linux/
70
stdin and stdout and Python
You have already read from stdin and written to stdout many times. Look
at the very simple program in a file called s1.py
line = input()
print(line)
When run from the command line this program waits for a line to be typed
in, and then prints it out to the terminal. By default input() reads from
stdin and print() outputs to stdout.
71
stdin and stdout and Python
The sys module allows you to be more explicit about the fact you’re
writing to stdin or stdout. This program does the same as the last:
import sys
line = sys.stdin.readline()
sys.stdout.write(line)
72
stdin and stdout and Python
Putting this in a loop, we can read and write as long as there is input:
% cat partCat.py
import sys
line = sys.stdin.readline()
while line:
sys.stdout.write(line)
line = sys.stdin.readline()
This program may seem silly and useless, but it can be somewhat useful
with file redirection:
73
stdin and stdout and Python
We can use it to show the contents of an ascii file:
$ python3 partCat.py <s1.py
line = input()
print(line)
We see s1.py contains the two lines of our earlier simple program.
74
stdin and stdout and Python
We can also use it as a very simple way to create a text file:
$ cat README
I typed this in
We tell Bash that we are finished with input from stdin by typing Ctrl-d
75
python and command line arguments
Our partCat.py program is almost like the UNIX cat command.
If cat is invoked with no arguments it also reads from stdin and
writes to stdout. However, if you can invoke cat with the names of
files it will read from those instead of stdin.
will print the contents of file1 followed by file2 followed by file3 to stdout
76
python and command line arguments
You can use the sys module to read command line arguments in a python
program. sys contains the list argv which is a list of the arguments. The
first element is the name of the program itself.
77
python and command line arguments
$ cat argReader.py
import sys
for arg in sys.argv:
print(arg)
78
A Simple Python Program acting like cat
$ cat myCat.py
import sys
if len(sys.argv) == 1:
line = sys.stdin.readline()
while line:
sys.stdout.write(line)
line = sys.stdin.readline()
else:
for i in range(1, len(sys.argv)):
f = open(sys.argv[i])
line = f.readline()
while line:
sys.stdout.write(line)
line = f.readline()
f.close()
79
Text Editors
•You will want to find a good text editor to create programs and test
files.
–You have done and will do much of this work using an IDE (Integrated
Development Environment) that usually combines a text editor, compiler or
interpreter, I/O display, and some kind of file management.
–But it is often useful or necessary to load up a program file in a text editor.
•You do NOT want to use a word processor for this work (like Word)
–A word processor includes information in the file about formatting
–A text editor just creates the ASCII text you write.
80
Text Editors
•You will probably want to learn a little bit about using a nongraphical
editor that runs on a terminal. Three common ones in UNIX are:
•emacs
•You may also want to learn and use an editor that uses windows and a
mouse.
–Notepad comes installed on Windows, but it is not good.
–UNIX and Windows (and MACs?) use different ASCII characters to mark the end
of a line. A good editor for programmers will let you convert these.
–Some editors do auto indent (can be a useful or a pain), color coding, and/or
bracket matching, etc.
•A FEW of the commonly used text editors are listed on the next slide
82
Text Editors
•Notepad++ WindowsFree
•Sublime Text All $70 (but unlimited free trial)
•BBEdit MAC Free limited version
(TextWrangler)
•Brackets All Free
•jEdit All Free
•Atom All Free
There are MANY more. Find one you like and learn to use it.
You may want to visit
https://en.wikipedia.org/wiki/Comparison_of_text_editors
83
The diff command
• The diff command looks for differences between files
• You will probably want to know this command since it will be used in
grading.
• It also can be helpful when you have two version of a program and want
to see how they differ.
84
Back to the shell – command line editing and shortcuts
bash supports simple command line recall and editing with the "arrow keys" but many control-key and
escape sequences have meaning too. Here are a few:
^A/^E Go to start/end of line.
^W Erase the last "word".
^U Erase whole line. (^C works, too.)
^R Do incremental search through previous commands.
ESC-f/b Go forwards/backwards a word. (Two keystrokes: ESC, then f)
ESC-. Insert last word on from last command line. (Very handy!)
85
Shell metacharacters
• Many non-alphanumeric characters have special meaning to shells.
• Characters that have special meaning are often called metacharacters. Here are the
bash metacharacters:
86
Shell metacharacters
• Many non-alphanumeric characters have special meaning to shells.
• Characters that have special meaning are often called metacharacters. Here are the
bash metacharacters:
87
Shell metacharacters
• Many non-alphanumeric characters have special meaning to shells.
• Characters that have special meaning are often called metacharacters. Here are the
bash metacharacters:
89
Examples of escaping
90
Wildcards
Observe:
% ls
a out x xy z
% ls ?
a x z
% ls ???
out
Wildcards, continued
•echo is also good for exploring wildcards, and uses less vertical space
on slides:
% ls
a out x xy z
% echo ?
a x z
% echo ??? ??
out xy
Wildcards, continued
% ls
a out x xy z
% echo ? ? ?
a x z a x z a x z
% echo x? ?y
xy xy
•Another:
• % ls
• Makefile fmt.c utils.c utils.h
• % echo *.[chy]
• fmt.c utils.c utils.h
The character set wildcard
•More:
•[A-Z]*.[0-9]
•Matches names that start with a capital letter and end with a dot and a digit.
•[Tt]ext
•Matches Text and text.
Lots more with wildcards
•The bash man page uses the term "pathname expansion" for what I've called
wildcard expansion.
•Another term that's used is "globbing". Try searching for "glob" on the bash
man page.
•Wildcards don't match hidden files unless the pattern starts with a dot, like
.*rc.
•There are other wildcard specifiers but ?, *, and [...] are the most commonly
used.
Pattern matching: grep
101
Pattern matching: grep…
(1)
102
Pattern matching: grep…
(2)
103
Pattern matching: grep…
(3)
104
Setting defaults for your commands
However the alias will only last during this session of your shell
105
Good news and bad news
•Good news:
• The behavior of bash can be customized by putting commands in the initialization files that
bash reads.
•Bad news:
• Several files and rules are involved.
• The initialization files present and their contents vary from system to system and user to user.
•We'll first talk about the mechanics of bash's initialization files and then look at types of
things we might add to initialization files.
•Anything that's valid at the bash prompt can appear in an initialization file and vice-versa. In
other words, initialization files simply contain a sequence of bash commands.
The rules (simplified)
•Common practice:
•(1) ~/.profile loads ~/.bashrc.
•(2) All customizations are in ~/.bashrc.
Shell variables
• bash supports variables that hold values of various types, including integers and arrays but we'll focus on
string-valued variables, which are the default.
• The variable PS1 falls in the first category. Its value specifies the primary bash prompt. You may have
noticed that the prompt looks different in the various shells I've shown, that's because this variable is set
different.
% echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/b
in:/sbin:/bin:/usr/games:/usr/local/rvm/bin:/ho
me/stdntwm/bin
PATH=$PATH:~/bin
–It's appendeing":~/bin" to whatever PATH already is.
•Like with any risk, you need to weigh risk vs. convenience.
•Pro: When developing scripts and programs, not having to type ./x is
convenient.
–Your account on lectura has dot in the path by default
–I have always have had dot in my path and never had a problem
–On your own machine, the danger seems nearly nonexistent
•Con: People with a lot of experience think the danger is real and many
recommend not including it.