Study Notes GNU Linux Command Line Interface
Study Notes GNU Linux Command Line Interface
Anthony A. Aaby
This is a free book; you may mirrow it, reproduce it, and/or modify it under the terms of version 2 of
the GNU General Public License as published by the Free Software Foundation whose website is located
at http://www.gnu.org/copyleft/gpl.html.
This book is an edited and expanded version of Linux Fundamentals: A Training Manual by Philip
Carinhas, Ph.D. of Fortuitous Technologies (www.fortuitous.com, [email protected]). The original
copyright is reproduced here:
Copyright c 2000-2001 Fortuitous Technologies, Inc.
Fortuitous Technologies Inc.
6909A Hardy Dr.
Austin, Tx 78757
USA
WWW: http://fortuitous.com
E-mail: [email protected]
This training manual is a free book; you may reproduce and/or modify it under the terms of version 2 of
the GNU General Public License as published by the Free Software Foundation whose website is located
at http://www.gnu.org/copyleft/gpl.html.
This book is distributed in the hope it will be useful, but without any warranty; without even the implied
warranty of merchantability or fitness for a particular purpose.
The author encourages wide distribution of this book for personal and commercial use, provided the
above copyright notice remains intact and the method adheres to the provisions of the GNU General
Public License located at http://www.gnu.org/copyleft/gpl.html.
In summary, you may copy and distribute this book free of charge or for a profit. No explicit permission
is required from the author for reproduction of this book in any medium, physical or electronic.
Note, derivative works and translations of this document must be placed under the GNU General Public
License, and the original copyright notice must remain intact. If you have contributed new material to
this book, you must make the source code (e.g., LATEX source) available for your revisions.
Contents
1 Introduction to GNU/Linux 5
1.1 Linux Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 Multi-User Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Why GNU/Linux? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 User Interface: Graphical User Interface vs Command Line Interface . . . . . . . . . . . . 7
1.5 Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2 Using X-Windows 9
2.1 X Display Manager, Window Managers and Desktops . . . . . . . . . . . . . . . . . . . . 9
2.2 Starting and Customizing the X Environment . . . . . . . . . . . . . . . . . . . . . . . . . 10
4 Text Files 27
4.1 Command Line Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.2 Vi and related editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3 Editing With Pico . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.4 Editing With emacs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.5 Using Mail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.6 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
8 Managing Filesystems 57
8.1 Creating Partitions with Fdisk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
8.2 Creating a Filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
8.3 Mounting Filesystems by Hand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
8.4 Swap Partitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
8.5 Automatic Mounting at Boot with /etc/fstab . . . . . . . . . . . . . . . . . . . . . . . . . 60
9 Process Control 61
9.1 Creating Foreground and Background Processes . . . . . . . . . . . . . . . . . . . . . . . . 62
9.2 Killing Processes With kill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
9.3 Managing Process Priorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
9.4 Cron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
10 Shell Scripting 69
10.1 Shell Initialization Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
10.2 Utility Shell Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
10.3 General Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
10.4 Script Automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
A Glossary 93
Introduction to GNU/Linux
• provides a complete development environment with C, C++, Java, editors, version control systems,
and built tools.
• is fully Open Source.
Linux
Workstation Server
Firewall
Documentation SQL
Communications
Video Samba
File
Audio
C/C++/Java/Perl/DB FTP Proxy
Graphics Httpd
Linux is a good solution for developers that need a stable and reliable platform that has open source code.
Linux has many GUI software development interfaces. Linux is ideal as a workstation also, and offers
many customizable features not found in any other platform. It makes a good platform for dedicated
workstaions that have limited functions like in an educational or laboratory environment.
1.5 Conventions
In order to take full advantage of this manual, students should execute every command that is listed in
the text as well as do all the exercises. The following is a list of conventions supported in this manual:
<bash>: indicates a command entered in the bash shell by the user. When you see this sign, you are
expected to enter these commands exactly as indicated and check that the results are consistent
with what is written.
<tcsh>: indicates commands in the tcsh shell. Most of these commands are to be completed after hours or
at home. Since Linux advocates freedom of choice, we wish to make students aware of this option
to bash.
Using X-Windows
The X-Windows system is the Linux answer to a graphical user interface or GUI. It allows
users a great interface to work from.
The X Window System (www.x.org), known simply as “X”, is a portable, network-transparent
client/server interface between hardware and the desktop environment. It is frequently used
in conjunction with the UNIX and Linux operating system. The current version of the X
Window System is “X11R6”. A freely available version of the X protocol for the Intel platform
is XFree86 (www.xfree86.org).
If your system is running X-Windows, there should be a prompt to enter a user name and
password. As the focus of this text is on the command line interface, this chapter is here for
completeness and may be skipped.
Desktops
CDE Uses the Motif libraries.
GNOME Uses the GTK+ libraries.
.gnome Configuration files.
KDE Uses the QT X-library.
.kde* Configuration files.
X-Display Managers
kdm KDE display manager
gdm Gnome displays manager
xdm X display manager
The following subsections provide a brief description of the desktops.
2.1.1 Gnome
Gnome is one of the two very popular desktops out there.
Lets look at Figure 2.1. First notice that the bottom panel has several typical icons like a tool-box,
terminal window, and netscape.
It has a four panel virtual display which gives you four whole screens to work in. This gives some room
to spread out. Inside the window we see some drop down panels that set the appearance. There is also
the file manager visible. There are click-able icons on the desktop itself, much like the other OS’s you
have used. Not too shabby for a free OS.
2.1.2 KDE
KDE is the other popular desktop. Figure 2.2 is a sample of what the KDE desktop looks like.
Notice that KDE also has four virtual panels to work on, and has all the bells and whistles a high quality
GUI would provide.
Basic X Tools
xterm [options] Start an X-Terminal
xclock [options] A basic wall clock
xman -options Display the manual X-style
xbiff -option Mailbox flag to keep you waiting for mail
xboard A chess game
xrdb -merge Xfile Incorporate Xfile into your environment
xload Show the system’s usage load
There are actually too many applications in X to list. Almost everything these days has an X interface.
Just about everything in X can be customized, depending on how hard you want to work on it. The
most simple thing you can do to customize your environment is to keep a defaults file, normally called
.Xdefaults located in your home directory.
A typical .Xdefaults looks like this:
!---------------------------------
! .Xdefaults X-Resource File
!---------------------------------
Netscape.Navigator.geometry: =700x700
XTerm*visualBell : on
XTerm*Font : 9x15bold
XTerm*scrollBar : on
XTerm*saveLines : 4940
XTerm*borderColor : white
xclock*geometry : 60x60-0+0
xclock*background : black
xclock*foreground : white
The initial instance in the variables is a class name. The subsequent variables in string are called X-
resources or just Resources which identify the property of the program or property to modify. The *’s
are wildcards and can match anything.
Finding what is and isn’t a valid X-resource can be difficult, but normally most man pages have a listing
of these and examples of how to set them. Once you have edited this file to your liking, you must activate
the changes by using the xrdb utility like this:
<bash>: xrdb -merge .Xdefaults
Afterwards, try a command to see if your changes take hold. Normally, there is an initialization script in
a system folder or in your home directory that will read your .Xdefaults for you when you start your X
session. This file is sometimes called .xinitrc and is easy to customize:
#!/bin/sh
userresources=$home/.Xdefaults
usermodmap=$home/.Xmodmap
sysresources=/usr/X11R6/lib/X11/xinit/.Xresources
This chapter introduces the commandline interface and commonly used commands.
1. X-Windows GUI interface. Open a shell or terminal window to use the command line interface.
2. Text-base terminal: A single use (at a time) Unix/Linux system or a text-based terminal on a local
area network (LAN).
3. Dialup/PPP connection: A connection to a remote computer through a dial-up interface. The local
machine provides either telnet or ssh to provide login to a text window interface.
4. Local area network (LAN) connection: The local machine provides either telnet or ssh to provide
login to a text window interface.
5. Internet connection: A local host provides access to a remote host through telnet or ssh.
<login:>: YourUserName
Password: - for security, nothing will be displayed.
When you log into your system with the login name and password given to you, you will see a prompt,
something like
<bash>:
You may see a variety of prompts depending the shell your are using and the set prompt command in
the .login file for the c-shell. Your system should always prompt you with the name of the shell (bash)
and your login name. This is a customizable feature in the bash shell which you are now using.
To logout enter the command logout, exit, or a period.
<bash>: logout
or
<bash>: exit
or
<bash>: .
You may change your password with the passwd command
The most basic command in Linux is the directory listing “ls” command. You can see the contents of
your account by typing
<bash>: ls -al
User level filesystem commands are covered in Section 3.4 and the essentials of the filesystem are covered
in Chapter 7.
<bash>: ls -l .bashrc
First comes the command name, followed by options. Options are normally preceded by a dash or minus
sign. There is always a space between the command and the dash. Some commands use no options at
all. After the options comes any other parameters or informations that command may need.
Let’s talk about some of the workhorse commands. Please note that these definitions are purposely
abbreviated and incomplete! For more details on each of the commands below, you can consult the online
manual using the man and info commands, see Subsection 3.3. In the commands below, parameters
that are enclosed in square brackets [...] are optional to that command. [-opts] refers to options in the
style just mentioned.
Printing
lp file System V print command
lpr [-Pprinter] file Print file using printer. See /etc/printcap for list of print-
ers.
lp -Pprinter file Print file using printer
lpr -Pprinter file Print file using printer
lpq [-Pprinter] Check the print queue
lpstat System V: Check print queue
lprm [-Pprinter] job# Remove job from printer queue
cancel job System V: Remove job from print queue
General Tools
. Current working directory
.. Parent directory
User’s home directory
cd dir Change cwd to dir (home if dir omitted)
cd .. Change cwd to parent directory
cd /path Change cwd using absolute path
cd path Change cwd using relative path
chmod perms files Change file permissions of files
When in doubt, use man and man -k keyword to get info on a command or UNIX related term.. Find
the man page for the ls command. ls will list directory contents:
<bash>: man ls
Here is a man entry for cd which changes your current working directory (folder).
<bash>: man cd
3.3.1 Exercises
1. <bash>: man man
2. <bash>: man 7 signal
3. Man cd and look for information on “.” and “..”
4. <bash>: cd .. ; pwd
5. <bash>: cd . ; pwd
6. <bash>: cd ; pwd
7. Discusss what “.” and “..” are in terms of the filesystem.
<bash>: ls file1
file1
<bash>: ls -l file1
-rw-r--r-- 1 joe users 0 Oct 28 22:05 file1
Using the -l flag causes a “long” listing that shows more information about file1.
You list your directories in a similar way (note that the second example shows that dir1 is empty).:
<bash>: ls -l
total 10
drw-r--r-- 1 joe users 0 Oct 28 22:05 dir1
<bash>: ls -l dir1
total 0
will copy file1 to file2. Copying a folder or directory requires the use of the recursive or -r flag
indicating that cp should decend into the directory and copy all sub-files and sub-folders:
<bash>: cp -r dir1 dir2
Exercise 3.4.4: Please create a directory like this now. Explain clearly how the following examples
are different from the above:
<bash>: cp file1 dir1
<bash>: cp -r dir1 dir2/
<bash>: cp -r dir1 dir2/dir3
Removing directories is also done with the rm command, but if the directory is not empty, you need to
use the “recursive” or -r option:
<bash>: rm -r dir1
After you try the above, make sure file1 and dir1 are gone. Empty directories may be removed with
the rmdir dir1.
3.5.2 Redirection
Redirection refers to the art of redirecting input and output traffic from commands. Shells like bash
allow for redirection of stdin and stdout with the < and > operators respectively.
As an example, lets say you want to list some files and send (redirect) the output to a file instead of the
screen. Do it the easy way:
Note that “cat output.txt” and “cat < output.txt” give the same result, but the ”wc -l”
examples give something slightly different.
In bash stderr is redirected with with the 2> operator, while in tcsh, the >& operator. Just relax and
we will see real examples of this shortly.
Linux Warning: Please note that > will overwrite anything in the output file, if it exists, or create the
file if it does not exist. In contrast, the >> operator will append to the existing file.
3.5.3 Pipes
When you want to take the output of one command and use that is input into another, use the “pipe
operator” | . Think of actually connecting a metal pipe from one command to another. The following
example sorts a simple ls command in reverse order (do it!):
<bash>: ls | sort -r
.doomrc
.cshrc
.bashrc
.acrorc
<tcsh>: tcsh
<tcsh>: (cat noname > output.txt) >& error.txt # Send stderr to error.txt
<tcsh>: more output.txt # Same as in bash.
<tcsh>: more error.txt # Just like in bash.
<tcsh>: cat testfile.txt >& out.txt # ditto
<tcsh>: cat < testfile.txt | sort | more # ditto
<tcsh>: locate .bashrc | xargs grep alias # find ‘alias’ in .bashrc.
<tcsh>: exit
Don’t forget the last “exit” to get out of tcsh and back into fabulous bash.
<bash>: ls /etc/h<TAB><TAB>
host.conf hosts hosts.allow hosts.deny httpd/
<bash>: ls /etc/h
The shell tells you what your choices are and is again ready for more input. This also works on commands
too:
<bash>: mo<TAB><TAB>
modemlights_applet montage mount.smbfs
modemtool more mouse-properties-capplet
modinfo morepgp mouse-test
modprobe mount mouseconfig
<bash>: mo
This shows us the possibilities, and again returns us so we can continue typing a command.
Remember that tcsh has the same possible-completion mechanism as bash does above. Just use <Ctrl-
D> instead.
The $ symbol allows bash to process the expression in-line and later provide the results to the echo
command.
Command History allows you to use stuff from your old commands in your current command. Remember:
recycling is good for the environment ♣. The following list shows the history reference syntax common
to both bash and tcsh:
!! Redo the last command. Same as !-1
!−N Repeat the N th most recent command (see next)
!−3 Repeat the 3rd most recent command
!N Redo the N th entry in the history list
!string Redo last command starting with the text “string”
!?string? The most recent command which contains the text “string”
On top of history referencing, you can add these modifiers to the shell command line by appending them
to the history reference after a colon (:)
3.6.4 Exercises
You can get a list of your history by typing simply history. Create two files called boogie.man and
boogie.man.old. The file contents are not important for this exercise. Try these examples of the above
history machinery to try. The exact history will vary depending on what you do so please adapt these to
your current situation:
<bash>: !-2
vi boogie.man
Text Files
diff file1 file2 List the differences between file1 and file2
cat list of files Concatentate files and sent to standard output
more file Display file one page at a time
less file Display file one page at a time and allow paging backwords
head file Display the first few lines of a file
tail file Display the last few lines of file
Printing
lp file System V print command
lpr [-Pprinter] file Print file using printer. See /etc/printcap for list of print-
ers.
lp -Pprinter file Print file using printer
lpr -Pprinter file Print file using printer
lpq [-Pprinter] Check the print queue
lpstat System V: Check print queue
lprm [-Pprinter] job# Remove job from printer queue
cancel job System V: Remove job from print queue
Text files may require special handling to print them on a postscript printer. The command
On occaision other applications (mail, write, talk) will display text over an editing session. Type CTRL-l
to redisplay your editing session.
4.2.2 To enter vi
at the system prompt, enter
• vi fileName or
• vim fileName
where fileName is either a pre-existing file or the name of a new file. You are now in the
command mode.
4.2.3 To exit vi
press ESC to make sure you are in command mode
• Open lines
– Type O to open lines
vi has 2 basic modes: Command mode, and Insert mode. First we will start to work on our project.
Basic command mode functions are listed below. Those with and star beside them indicate commands
which enter insert mode.
These commands may not seem obvious from a mnemonic point of view, but were designed for simplicity
and keyboard efficiency.
You can read and write files in command mode by using ex mode which is invoked by typing : (which
will prompt you at the bottom of the vi screen)
Once we get familiar with vi we will discuss these modes further. The first thing to do is to start the
editor by typing the following:
<bash>: vi input.txt
˜
˜
˜
The i puts you into insert mode, and the final <esc> puts you back into command mode. Now write
and quit by doing a :wq
^G Get Help ^O WriteOut ^R Read File ^Y Prev Pg ^K Cut Text ^C Cur Pos
^X Exit ^J Justify ^W Where is ^V Next Pg ^U UnCut ^T To Spell
The only problem with pico (and other non-vi editors) is that it may not be on your system in an
emergency situation, which is when you need it the most. Hit ^X to exit pico.
emacs Formatting
indent current line (mode-dependent) TAB
indent region (mode-dependent) C-M-
indent sexp (mode-dependent) C-M-q
indent region rigidly arg columns C-x TAB
emacs Help
basic help C-h
scroll help window C-M-v
emacs Tutorial C-h t
apropos: show commands matching a string C-h a
show the function a key runs C-h c
describe a function C-h f
4.5.1 Elm
Fire up elm by typing “elm”. When it first starts, it will ask you some questions about files, just say
yes to all.
Command:q
Once inside elm, just hit “m” at the command prompt, and follow the signs. elm is more command
driven and UNIX -like. When in doubt, just keep hitting “q” for quit. Use the arrow keys to go up and
down the message list.
4.5.2 Pine
Pine is easier to learn and use, and is compatible with elm, so you can use them interchangeably. Use
the up-arrow, down-arrow, <, and > arrows to navigate.
RE ::= c | RE RE | RE + RE | RE*
UNIX extends regular expressions with additional metasymbols and extensions to the regular expression
notation. Regular Expressions are search patterns that give you control over how text patterns are found.
Here are the basics pattern matching symbols:
. Match any single character. ‘‘.*’’ matches anything any number of times. See *
* Match the last char or exp 0 or more times. a* matches (), a, aa, aaa,
+ Match the last char or exp 1 or more times. a+ matches a, aa, aaa, ..
? Match the last char or exp 0 or 1 time. a? matches (), a
^ Match the beginning of the line. ^abc matches lines starting with abc.
$ Match the end of a line. ^$ Matches empty lines.
[] Match chars inside. [abc] can match a, b, or c or in a range [A-Z].
[^] Negates the match chars: [^abc] matches anything except a, b, or c.
() Char grouping. (abc)+ matches abc, abcabc, abcabcabc, ....
\ Match regex chars like \+, \*, and \^.
{n} The preceding item is matched exactly n times.
{n,} The preceding item is matched n or more times.
4.6.1 GREP
grep is a pattern search tool. It will find patterns in a file and print it on the terminal. These patterns
are regular expressions as well. Test grep with the file as before.
4.6.2 AWK
Awk is a pattern scanning and process language. Its Syntax is
When the program is long, it is usually more convenient to put it in a file and run it with a command
like this:
Take a look at the manual now. Here are some one-liner examples:
This program prints a sorted list of the login names of all users.
awk ’END { print NR }’ input.txt
This program counts lines in input.txt.
awk ’NR % 2 == 0’ input.txt
This program prints the even numbered lines of input.txt.
If you’d use the expression ‘NR % 2 == 1’, it’d print odd numbered lines.
awk ’{if (length($0) > max) max=length($0)} END {print max}’ input.txt
This program prints the length of the longest input line.
awk ’length($0) > 80’ input.txt # Print lines longer than 80 characters.
Since the sole rule has a relational expression as its pattern,
and has no action, the default action, printing the record, is used.
awk ’BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }’
This program prints seven random numbers from zero to 100, inclusive.
ls -lg *.txt | awk ’{ x += $5 } ; END {print "total bytes:" x }’
This program prints the total number of bytes used by all .txt files.
4.6.3 Perl
Perl, “Practical Extraction and Report Language” is the Swiss Army Knife of all scripting languages.
It has everything except a Megawatt laser, and a kitchen sink. Perl has a very complete set of regular
expressions and a large set of UNIX system calls that make it a steroid-pumped tool:
Even though complex, we can learn a few perl one liners that work miracles:
4.6.4 SED
sed is a stream editor, which means that it works like a conveyer belt on your terminal. The text flies
past you while it works.
sed is complex so we’ll just show some simple usage and examples:
In Linux and UNIX , you carry many local attributes that control how your immediate shell
interface interacts with the system. These attributes are called Shell and Environment Vari-
ables, and they are critical to Linux operation. UNIX and Linux use many variables for internal
processing. These help the system manage resources for users. This chapter discusses the bare
necessities that all Linux survivalists need to know.
A user can control fundamental aspects of his/her environment by setting shell variables as you work,
or inside of a startup script file which gets invoked when you login to your account. Simple examples
common to each shell are your prompt (the thing that stares at you and waits for your commands) and
aliases. An alias is a shorthand for some other command which a user can define, normally in the shell
startup files like .bashrc and .cshrc. We’ll work with these concepts very shortly.
5.2 Bash
Bash is the default shell for Linux . The default shell is like an environment where all the basic commands
come from bash. Let’s look at the bash manual page:
PRINTER=astro
PS1=<\s>:
PS2=>
PS4=+
PWD=/home/joe
SHELL=/bin/bash
SHLVL=2
TERM=vt100
Symbol/Command Action
> Redirect output
>& Redirect stdout and stderr
>> Append output to file
| Pipe output
& Run process in background
TAB Filename/command completion
!n Repeat command #n in history
$var Variable substitution
# Comment line
bg Put process in background
fg Put process in foreground
cd Change directory
echo Echo execution output
jobs List current shell processes
kill Kill specified processes
umask Set default file permissions
PROMPTING
When executing interactively, bash displays the primary
prompt PS1 when it is ready to read a command, and the
secondary prompt PS2 when it needs more input to complete
a command.
Lets change the bash prompt by adding the command number. This is an example:
Now lets set your prompt so that it always displays your path. Even though this manual will specify
<bash>: , you should still use a prompt like this:
<bash>: PS1=’<\w>: ’
<bash>: tcsh
<tcsh>: alias d ’ls -Agl’
<tcsh>: d
.............
<tcsh>: exit
Your current working directory (cwd) is where all files are sought and written by default. uid and gid are
the numerical values for your user and group, which identify you as a user and group member respectively.
Your home is where you (and your files) live, and your path is where you look for your prey (executable
commands).
You can always determine your cwd with the pwd command. Your cwd is always referred by the “dot”
(.) symbol, and the directory directly below is referred to by the double-dot (..) symbol as in the result
of an ls -Agl:
<bash>: ls -gl
total 608
drwxr-xr-x 2 joe user users 1024 Dec 20 19:09 .
drwxr-xr-x 15 root root 1024 Dec 10 19:04 ..
-rwx------ 1 joe user users 3185 Dec 19 15:51 .cshrc
-rwx------ 1 joe user users 3185 Dec 19 15:51 .bashrc
-rw-r--r-- 1 joe user users 33 Dec 20 10:49 doubletake
drwxrwxrwx 1 joe user users 33 Dec 20 10:49 mail
Note that “..” refers to /home when you are in your home directory /home/joe user. The first character
in the long file listing is the file type, which tell us what kind of animal we have. Also ∼ refers to your
home directory in your prompt, and changes to the /fully/qualified/path only when moved out of
/home/joe user .
NAME=value
export NAME
export NAME=value
5.3.2 Exercises
Exercise 1
Find the hostname of your machine and replace “groucho” in the DISPLAY variable as above.
Exercise 2
<bash>: tcsh
<tcsh>: setenv PATH /bin:/sbin:/usr/bin:/usr/sbin
<tcsh>: setenv DISPLAY groucho:0
<tcsh>: setenv EDITOR /bin/vi
<tcsh>: env
Once this is done, bash will look in your own /home/user/bin folder to find any commands you put
there. This is a good thing which will come in handy later when we work on scripting.
5.4.1 Exercises
Set your path in tcsh by editing your .login file, and add ∼/bin to your path.
tcsh uses its rehash function to re-read all the folders in your path and find the new commands.
which will spawn a new shell (on top of the old one) with your default group given by groupname. For
this trick to work, you must belong to this group to begin with.
Once you are in this new group state, all process and files created will carry the group name as well as
your user name. Having multiple groups can be useful when accessing restricted hardware or working in
a team of developers, where everyone needs access to common software and systems.
To exit this group-shell, simply type exit.
5.5.1 Exercises
1. Look at the files /etc/passwd and /etc/group. Determine how groups are created and assigned
with the help of the manual pages. Write your observations down here.
• ls -l
• Protection bits: u - user, g - group, o - other.
[-dl] rwx rwx rwx
• chomd mode filename
chmod who op permissions filename
Examples: chmod go-w ..., chmod o+x ..., etc
• umask - set file creation mask (ppermissions taken away; in .login file.
• chown – must be performed by root
• ln -s q sl – create a symbolic link sl in working directory to file/directory q
6.1 Security
The primary concern is integrity. Accuracy or validity is fundamental and security is secondary. Security
is protection against unauthorized disclosure, alteration, or destruction of data and protection against
unauthorized use.
6.3 Cryptography
6.3.1 SSH, SCP, and SFTP
6.5 Privacy
6.5.1 Privacy-Enhanced Electronic Mail (PEM)
Filesystem Essentials
In this chapter, we will learn how to master files and filesystems. This is a very important
aspect of Linux , and is used constantly.
7.1.1 Exercises
1. The tree diagram above is not correct for a modern version of Linux. Find and compare the
differences with your system and write down your results.
2. The /proc filesystem is a special on that has direct access to the system kernel. The files in /proc
have no size, but what happens if you do the following:
<bash>: cat /proc/cpuinfo
<bash>: cat /proc/pci
/ bin
dev
etc
home mary
jane
lib joe
proc
tmp
usr X11R6
bin
etc
include
lib
local bin
man emacs
spool etc
lib
src linux
tmp
link number
user ID
group ID
Size
Month
Day
Time
File Name
Its entry gives us a lot of information. It has all of its access entirely open, so everyone can read, write,
and execute. Also note that the first attribute listed is its type, in this case a “d” for directory. File
attributes for restricted (plain type) files are listed as dashs (-).
The next 9 parameters are file permissions or access parameters In UNIX , files have 3 sets of 3 access
parameters or “permissions”. The first 3 are for the owner, the second 3 for the group, and the last 3 for
“other” or the “world”. The permissions are read (r), write (w), and execute (x). When you look at a file
listing in long format you will see these attributes listed as (r,w,x) or omitted with a “-” in their place.
If the attributes are present, access is granted to for that action, otherwise access is denied.
Other major file types include symbolic links (l), an internal reference to another file, and plain files (-).
The following table summarizes native Linux file types as listed by the find command. Note that the
plain file permission never lists by ls as (f) but as a dash (-).
[ugoa][+ - =][rwx]
u --> user
g --> group
o --> others
a --> all
You can add (+), subtract (–), or exactly set (=) the mode. Examples:
MODE can also be an octal representation which represents the absolute mode:
The trick with octal is that you can add up the different numbers to get all different combinations of
privileges like:
7.3.1 Exercises
1. On directories, the execution privilege allows for access into the directory, so having just read and
write (rw) privilege is not enough. Only execute privilege will allow any access to anything inside
the directory. Try this out by doing a
Note that chgrp can change the group at the same time as in the following examples.
<bash>: chown johnson mail # Sorry, only johnson or Root can do that.
chown: mail: Operation not permitted
<Super>: chown joe user.users mail # Change owner to joe user and group to users.
<Super>: chown joe user.bozos mail # Change owner to joe user and group to bozos.
chown: mail: Operation not permitted # You’re not a member of bozos group!
<Super>: chown .testers mail # Ok, you are in the testers group.
chgrp is less powerful and not really needed but should be noted. Its syntax is
Here is an example.
7.4.1 Questions
Why can’t you change ownership of someone elses files? Who can do this? Is this a good or bad feature?
7.4.2 Exercises
1. Log in as root and change the owner and group of some files in the /tmp directory. Make sure you are
in /tmp and not /home/you/tmp or some other place.
7.5 Devices
In Unix (almost) all commands and hardware are represented by files. The hardware devices are fun-
damentally different and live in the directory /dev. Device files allow access to the hardware directly
through the kernel.
These special files have major and minor numbers that identify them in the Linux kernel. Major Device
Numbers specify a particular driver for I/O redirection in the kernel, and Minor Device Numbers specify
a device to be accessed by that driver. A typical example is the /dev/hda hard-drive:
It has a major number 3 and minor number 0. The leading “b” indicates that this is a block device. It’s
owner is root and its group is disk .
Do an ls -agl /dev to see the major and minor numbers of typical devices.
We list the most commonly used devices below. Note that N will represent an integer number.
/dev/null is a funny device that swallows everything you feed it like a black hole, so don’t put anything
there that you want back. It’s very convenient for swallowing up unwanted error messages like this:
We will learn the meaning of the preceding example in the next section. The cat command prints a text
file to the console and the cp command copies one file to another. Try this example
7.5.2 Exercise:
<bash>: ls -l /dev | grep ˆc
<bash>: ls -l /dev | grep ˆb
<bash>: ls -l /dev | grep ˆl
<bash>: ls -l /dev/hda*
<bash>: ls -l /dev/sda*
7.5.3 Discussion
Managing Filesystems
Creating and mounting filesystems is essential for disk access. The following sections discuss
the essential elements. Most of the commands we use are only accessible by the SuperUser
(root), so you must be logged in as such.
Filesystem Management
du
df
dd
fdisk
mount
sync
umount
mkfs
mkswap
swapon
Command (m for help): w (write the new partition info and exit)
The partition table has been altered!
Where the -t ext2 tells mount that the filesystem type is an ext2 filesystem, the default Linux filetype.
/alt is the mount point and /dev/fd0 is the device to be mounted. Go into /alt and see if you can
write on that partition.
To remove a filesystem, use the umount command:
The device can be either a partition or a file. Consult the man page now for mkswap options. A swap
partition is prepared in the following way:
which will make a swap file of 8192 blocks (8MB) from /dev/zero and put it in the file /swap in your
root directory.
We used the sync command after mkswap to force the format information to be written to the filesystem,
otherwise the system may take its sweet time to do so. sync ensures that /swap gets written before a
crash or system failure.
# /etc/fstab
# device Mount Point Type Options Freq Pass
#
/dev/hda1 / ext2 defaults 1 1
/dev/hda2 /usr ext2 defaults 1 2
/dev/hda3 /home ext2 defaults 1 2
/dev/hda7 none swap defaults 0 0
/dev/cdrom /mnt/cdrom iso9660 noauto,ro 0 0
Edit this file now and add an entry for our hand-mounted filesystem for /dev/fd0 above. Once this is
done, you can abbreviate the mount command for it by simply doing
<Super>: mount /alt
Mount will look inside of /etc/fstab and get all the required information that it needs to do its work.
You can override /etc/fstab by specifying all the information as before.
Linux will automatically mount all the files listed correctly in /etc/fstab at boot time.
Process Control
In this chapter we will learn how to control your processes both interactively and non-
interactively. It is very important to maintain control of your system and manage unruly
processes.
The program design philosophy under Unix is to treat each program as a filter which takes its
input from the standard input file and sends its output to the standard output. By default,
the standard input file is the keyboard and the standard output file is the display screen.
Programs can be strung together using pipes. A pipe takes the output of one program and
redirects it to become the input for another program.
The jobs displays all jobs in the shell along with their number and status. The kill -9 %N kills job
number N . The flag (-9) is needed to force a “sure kill” which is sometimes needed. The ampersand
symbol (&) is what you would use to put a command directly into the background with xterm &.
Be careful because some commands want to write errors to the standard output stdout and that could
cause strange results on your screen. To avoid this, you can redirect stdout to /dev/null (or a log file)
AND put it into the background in one gulp:
<bash>: ps
PID TTY TIME CMD
683 ttyp1 00:00:00 bash
31666 ttyp1 00:00:00 xterm
32716 ttyp1 00:00:00 xclock
<bash>: ps -agl # Get a long list with ps
F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND
000 501 683 672 13 0 2220 804 rt_sig S ttyp1 0:01 [bash]
000 501 31666 683 0 0 3012 1900 wait4 S ttyp1 0:00 xterm -cr r
000 501 32716 683 0 0 2572 1304 do_sel S ttyp1 0:00 xclock
<bash>: top
42 processes: 40 sleeping, 2 running, 0 zombie, 0 stopped
CPU states: 2.3% user, 0.7% system, 0.0% nice, 96.8% idle
Mem: 63484K av, 52328K used, 11156K free, 18020K shrd, 2896K buff
Swap: 220316K av, 4964K used, 215352K free 28804K cached
PID USER PRI NI SIZE RSS SHARE STAT LIB %CPU %MEM TIME COMMAND
664 root 18 0 14824 14M 1540 R 0 1.1 22.7 18:21 X
31797 carinhas 9 0 7060 7060 3276 S 0 0.0 11.1 0:16 xemacs
464 carinhas 0 0 6020 6020 3596 S 0 0.0 9.4 0:03 netscapex
31666 carinhas 0 0 1900 1900 1440 S 0 0.0 2.9 0:00 xterm
32716 carinhas 0 0 1304 1304 1096 S 0 0.0 2.0 0:00 xclock
... <Shift-M> Sorted by memory usage....
Ctrl-C <quit>
Now I have located a renegade process called xclock which seems using way too much memory according
to the top utility. For example, if you want to kill process 32716, do the following:
Study also the man pages for killall, pstree, and proc for the LPI exams.
Next is an abbreviated manual page for kill, but beware that most shells have their own built-in version
of kill.
<bash>: ps -xl
F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND
000 501 617 612 0 0 2032 504 do_sel S ? 0:03 fvwm
000 501 622 617 0 0 3144 872 do_sel S ? 0:01 xterm -cr r
....etc....
There are two major tools for manipulating process priorities, nice and renice. nice lets you specify
the priority for a command initially, and renice allows you to change the priority after the process is
started. Here’s an exercise for you:
9.3.1 Exercises
<bash>: xclock -rv &
<bash>: nice -10 xclock -rv &
<bash>: /bin/nice -n 10 xclock -rv & # Same as above
<bash>: ps -xl
F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND
000 501 617 612 0 0 2032 504 do_sel S ? 0:03 fvwm
000 501 622 617 0 0 3144 872 do_sel S ? 0:01 xterm -cr r
000 501 2855 1321 8 4 2568 1300 do_sel SN ttyp2 0:00 xclock
2855: old priority 4, new priority 20 # Don’t worry if numbers don’t jive.
<bash>: ps -xl
F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND
000 501 617 612 0 0 2032 504 do_sel S ? 0:03 fvwm
000 501 622 617 0 0 3144 872 do_sel S ? 0:01 xterm -cr r
000 501 2937 1321 19 19 2568 1300 do_sel SN ttyp2 0:00 xclock
Note that you can only renice to a higher number (thus lower priority) so the system gives an error
message. Also, the listed PRI takes time to adjust to the NI (nice) value.
TCSH(1) TCSH(1)
Builtin commands
nice [+priority] [command]
9.4 Cron
Cron is a daemon that can automate tasks by periodically running them based on a time scheme. Its very
useful for maintenance tasks. Cron takes a filename as a script for input that it incorporates internally
and checks periodically. The file is called a crontab file.
Stars (*) are wildcards which always match, and rely on the other parameters to give cron timing queues.
If you want to execute every day, just put a * in the day column.
A simple example of this would be to run a script above at 12 midnight every night:
Notice that we have carefully routed stdout to a log file, otherwise cron could hang the job, or send us
all the error by mail.
Another interesting property of the cron time spec is it’s ability to specify numbers in a modulo fashion.
Just divide a * by a number to get cron to execute a periodic command:
You may also edit the current crontab file with the crontab -e command, which will throw you into
your default editor. When you exit, the crontab file is automatically updated.
<bash>: crontab -r
<bash>: crontab -l
9.4.4 Exercises
Exercise 1:
Create a simple script named hello that prints out “hello joe user”. It should only have two lines:
#!/bin/bash
echo Hello joe user you slacker...
This file should be placed in your personal ∼/bin directory, and should have the appropriate file mode
for execution (hint: chmod). Make sure to test this script by hand before you go on.
Exercise 2:
Now create a crontab file named crontab-file that will execute hello every 2 minutes. Submit this
crontab file as discussed above and check your mail on the even minutes to see if the scripts work.
Note: Cron’s default behavior is to send any unhandled output to your mail. If mail is not working for
some reason, you may send your output to a file or to your screen.
Shell Scripting
There’s nothing more aggravating than having to type out long commands over and over again. Shell
scripts are simple text files that list shell commands into a convenient “tool” which you can use more
easily than typing in all those commands over and over.
Now that we know enough shell workings to be dangerous, we need to focus our attention to making
changes permanent. It is essential to have easy to use environments and scripts to do complex tasks,
because otherwise we are stuck repeating numerous small commands daily. The natural starting point is
to customize our .bashrc and .cshrc files with a few aliases and a prompt or two.
The $* represents all the remaining variables on the command line except for the calling command. It is
equivalent to all subsequent command line variables, “$1 $2 ...”.
After you modify .bashrc you must do a “source .bashrc” to initialize your changes. Type alias
to see what the system’s definitions, and try out our new aliases.
Remember we can also have a .bash profile which is supposed to carry your environmental variables:
# .bash_profile
# Get the aliases and functions
if [ -f ˜/.bashrc ]; then
. ˜/.bashrc
fi
The term set a=$0 refers to the 0th component of the command line, which is the command file,
phone.csh, in our case. The $a:t instructs csh to remove all the leading pathname components,
since we are uninterested in seeing the full path. Test this by invoking the name of the script:
<bash>: phone.csh
Usage: phone.csh Name
Now your script should print each filename you enter on the command-line, as a check in our progress.
Again, test this script and check that the loop works:
/home/joe user/address/red
/home/joe user/address/green
/home/joe user/address/blue
Now that we know it works, replace the echo command with the correct cat phrase. While we are at
it, we will check for the existence of each file with the ( -e filename ) test. The previous foreach clause
should NOW look like:
Lets check our program by creating an /address directory and several files there...
10.2.3 Exercises
Exercise 1: Make the phone.bash version above work.
Exercise 2: Add an extra error message line if the file does not exist.
#! /bin/csh -f
# This script remove double in a sorted file. See the uniq manual.
set file1 = $1 # $1 is going to be the filename.
cat $file1 | awk ’{ if ($0 != last ) {print $0; }; }{ last = $0; }’
The script first stores the first command argument in $1’. It then cat’s the file into awk. Notice you
need the initial line of
#! /bin/csh -f
to tell the system that this is indeed a csh script.
Now the script that awk uses does 2 things. It first checks to see if the variable last was seen, if not,
prints it. The second thing it does is to store the current line in last. Of course you could just type the
whole second line into the command line, but that’s not much fun if you have to do it 9 times a day.
#! /bin/bash
# This file is named backup.sh
cd /home/guest # Make sure you are at home.
/bin/tar cvfz /mnt/fd0 . # Back up your home directory
echo All done boss!
In this example, we have specified all paths to commands. This is required since your normal path/shell
is not invoked in a script like this one. This script will create a lot of output which must be sent into a
log file or /dev/null later when we make our crontab file.
10.4.3 Exercises
Ex 1: Once you are confident that your script will run on its own two feet, you are ready to set it up with
cron. Create a crontab file /home/guest/crontab.backup and submit it with
<bash>: crontab crontab.backup
as done in section 9.4. Ask for help if you get stuck.
Linux comes with all the TCP/IP networking goodies you would expect from a full-featured
UNIX box. It has telnet, ftp, mail, and many other services. Here’s a quick list of the
bread-n-butter commands:
Networking Terms
TCP/IP Transmission Control Protocol / Internet Protocol
udp Best effort packet delivery protocol
tcp Reliable byte stream protocol
rpc Remote procedure call
ARP Address Resolution Protocol
route a network route to another machine
host Any machine on the network
client The host that wants data or a service
server The host that provides data or a service
Email
.forward File in user’s home directory containing mail forward-
ing address
mail user[@RemoteHost] [¡ file ] Mail user agent
pine Mail user agent
elm Mail user agent
mutt Mail user agent
System Information:
hostname -f Set or show the system’s host name
hostid Report the numeric identifier of the local host
uname -a Report system information
uptime Report time since last reboot
du -h Estimate file space usage at and below the cwd
df -h Report file system disk space usage
ps aux Report process status
top Report top processes
Superuser/Root:
su [user] Switch to different user (user must be in /etc/passwd
file)
sudo command Execute command as root (User must be in
/etc/sudoers file)
chown owner : group file Change file/directory ownership
halt This and the next two commands reboot the system
(must be superuser)
reboot
shutdown
Ctrl-Alt-Delete Reboot the sytem
TCP/IP Diagnostics:
Some of these commands may require Superuser priviledges.
/etc/hosts Static table lookup for host names.
/etc/resolv.conf Static table with name of the DNS
/etc/services Internet network services list.
hostname -f Set or show the system’s host name
ifconfig Display or configure local TCP/IP network interface con-
figuration
ping RemoteHost Send a “ping” to a remote host to check connectivity
traceroute RemoteHost Print the route packets take to network host
ipmaddr
iptunnel
arp Display or modify IP-to-Physical address translation ta-
bles used by ARP
rarp
route Print out the local routing table (check /sbin/route)
dig RemoteHost Send domain name query to DNS
nslookup RemoteHost Send domain name query to DNS
tcpdump -i ethX Listen to network traffic on ethX
ethereal Capture and analyze network traffic
netstat Display protocol statistics
netwatch Monitor network connections
nmap Network exploration and security monitoring
whois Client for the whois directory service
FTP examples
• ftp hostname
Name userName
Password userPassword
This shows that the host groucho is alive and well. It provides us with some timing information which
indicates the speed of the connection between LocalHost and RemoteHost.
If your DNS (see next section) is not working, you may not be able to ping by name, but perhaps by
number. You can also ping by IP number like this:
If you don’t get any response, or do get an error, something is wrong with the network and you will not
be able to communicate with that computer.
Name: www.io.com
Addresses: 199.170.88.21, 199.170.88.41, 199.170.88.39
Nslookup tells us there are 3 names that go with www.io.com. Large sites like www.io.com and
www.yahoo.com often have many numbers because they maintain several servers to handle all the re-
quests to their very busy sites. The server flure.pair.com is our DNS server as seen by our local DNS
setup.
DNS can also translate numbers into names:
Name: www-02.io.com
Address: 199.170.88.21
This was one of the www.io.com sites listed in the first example. If DNS can’t find your name, there is
little chance you can connect through the internet to it:
Sorry, you are SOL. No can do.. (unless you know the number already) Maybe try www.belse.com.
Sometimes you can connect by IP number even when DNS doesn’t work. Try to connect to www.io.com
with one of the numbers we found. Note that Linux has a text browser called Lynx that is many-times
convenient.
and on the local machine a complimentary setup allows you to work from there.
rlogin RemoteHost
Last login: Sat Jan 15 02:53:13 from beppo
You have mail.
[RemoteHost]/home/joe user:ls -agl
total 3236
drwxr-xr-x 20 joe user users 4096 Jan 14 09:45 .
drwxr-xr-x 5 root root 4096 Jan 14 08:42 ..
-rw------- 1 joe user users 1748 Jan 14 06:59 .ICEauthority
-rw------- 1 joe user users 101 Jan 14 08:35 .Xauthority
-rw-r--r-- 1 joe user users 1506 Jan 14 08:18 .Xdefaults
-rw------- 1 joe user users 133 Jan 11 15:56 .bash_history
....etc....
Remember that RemoteHost and LocalHost need to be changed to whatever your workstation is named.
What you should have now is a process that is run by the remote system! It should be clear that this
is powerful. In the next chapter we’ll talk about other networking features.. If you put a line like the
following in your .login or .bashrc, your DISPLAY variable will be set automatically for you. Play with
this for a second:
Program Development in
Unix/Linux
#include <stdio.h>
int main() {
printf("running my first program\n");
return(0);
}
Compile program
<bash>: cc try.c
Run program
<bash>: a.out
Print program
<bash>: lpr try.c
Capture program and output
<bash>: script
<bash>: cat try.c
<bash>: cc try.c
<bash>: a.out
<bash>: exit
Print session
<bash>: lpr typescript
– trace
file’s time stamp field (last-modified time). The makefile consists of suffix definitions, macro definitions,
dependencies, and commands. Each command behaves as if it were invoked within a shell.
Entries in a makefile have the form:
target : prerequisites
(tab) commands
where both the prerequisites and commands are optional. The commands are executed only if the target
is not upto data with respect to the prerequisites. The target is dependent on one or more files called
prerequisites each of which may have other files as prerequisites. The description file defines all of the
intermediate steps necessary to accomplish the task. The first character of a command line must be a
tab and no other line may begin with a tab. The following command may be used to check the tabs in
the description file.
<bash>: cat -v -t -e makefile
or simply
<bash>: cat -A makefile
The makefile is run by entering the command
<bash>: make
or
<bash>: make target
The make utility determines what parts of a program need to be rebuilt and then carries out the appro-
priate set of actions producing the latest version of the target.
For more details than are provided in this section, see [4] or visit the GNU Project web site server:
www.gnu.org/software/make/make.html.
The example in Subsection 12.3.3 is a portion of the makefile used in the preparation of this text.
Commands
Additional commands may be placed on separate lines or separated with semicolons if placed on the same
line.
Dependence Rules
target : prerequisites
(tab) command
The prerequisites may be placed on separate lines provided the previous line ends in a backslash. The
list of prerequisites may be followed by a command which is either preceded by a semicolon or entered
on a new line.
Macros
NAME = string
It is customary to use all caps in the name of the macro. A tab may not precede a macro definition and it
is terminated by a new line. A macro must be defined before is it used and it is referenced by ${NAME}.
Suffix Rules
.suffix.suffix :
(tab) command
Files ending with the first suffix can be prerequisites of files that have the same name but end with the
second suffix. No spaces are allowed between the suffixes. The command used to transform a file with
the first suffix to one of the second suffix may be placed on the next line. See the example in subsection
12.3.3.
The suffix dependences for C and C++ are built into make so need not be used.
# Macro definitions
SHELL = /bin/sh # Limit commands to Bourne shell
# Subdirectories
COMP = Compiler
DOC = DocPrep
FDIR = Fundamentals
PROG = Programming
# Fundamentals
fundamentals.tex : definitions.tex defsAaby.tex\
${FDIR}/X-Windows.tex\
${FDIR}/bibliography.tex\
${FDIR}/commandline.tex\
${FDIR}/copyright.tex\
${FDIR}/environment.tex\
${FDIR}/filesystem-management.tex\
${FDIR}/filesystem.tex\
${FDIR}/glossary.tex\
${FDIR}/introduction.tex\
${FDIR}/process.tex\
${FDIR}/scripting.tex\
${FDIR}/security.tex\
${FDIR}/software.tex\
${FDIR}/tcpip.tex\
${FDIR}/terms.tex\
${FDIR}/text-tools.tex\
${FDIR}/unixCommands.tex
touch fundamentals.tex
<tr>
<td colspan="2">CVSAREA={\it sandbox}<br />
CVSROOT={\it sourceRepository}</td>
<td>.profile or .bashrc file environmental variable entries for sandbox
and source repository respectively.</td>
</tr>
<tr>
<td colspan="2">setenv CVSAREA {\it sandbox}<br />
setenv CVSROOT {\it sourceRepository}</td>
<td>.cshrc file environmental entry for sandbox and source respository
respectively.</td>
</tr>
<tr>
<td>cvs</td>
<td>[-d {\it sourceRepository}] init</td>
<td>Create the source repository</td>
</tr>
<tr>
<td>cd<br />
cvs</td>
<td>$CVSAREA/{\it projectDirectory}<br />
import -m {\it msg repository vendor release}</td>
<td>Check project files into repository from the sandbox.</td>
</tr>
<tr>
<td>cd<br />
cvs</td>
<td>$CVSAREA/{\it projectDirectory}<br />
checkout {\it projectDirectory}</td>
<td>Check project files out of the repository and into the sandbox.</td>
</tr>
<tr>
<td>cvs</td>
<td>commit -m msg file</td>
<td></td>
</tr>
compress file compressedFile.Z The compress utility. Compressed files should have a .Z suffix.
uncompress file.Z The uncompress utility.
gzip file zippedFile.gz The GNU zip utility. Zipped files should have a .gz suffix
gunzip file.gz The GNU unzip utility.
The tar (tape archive) utility is used to construct a linear representation of the unix hierarchical file
structure and restore the hierarchical structure from the linear representation. In addition, it may be
used to compress and decompress the files. It was originally designed to save file systems on tapes as a
backup.
tar cf theArchive.tar theDirectory - creates a tar file of theDirectory and its contents an
places it in the working directory.
tar cfz theArchive.tgz theDirectory - creates a gziped tar file of theDirectory and its contents
an places it in the working directory.
tar xf theTarFile.tar - extracts the tar file into the working directory, duplicating the tarred
directory structure.
tar xfz theTarFile.tgz - gunzips and extracts the tar file into the working directory
tar tzf theTarFile.tgz - List of the contexts of the tar file
tar xf theTarFile FileOfInterest - extract the file of interest from the tar file.
12.7 Exercises
1. Create makefile for a small C or C++ program. The program should consist of several files. Your
makefile should insure that only the necessary files are recompiled after changes.
2. Package the program and makefile of the first exercise in a gzipped tar file.
Glossary
Commands are found in several different locations as specified by the filesystem hierachy standards FSH
2.2; see www.pathname.com/fhs. Not all commands in the standard are listed here. Not all commands
listed here are covered in the text.
lp Print files
ls List directory contents (also dir and vdir)
lynx Text terminal browser for the WWW
m4 Unix macro processor
make Utility to maintain groups of programs
man Format and disply the on-line manual pages
mkdir Make directories
mv Move (rename) file
nasm Portable 80x86 assembler
nice Change execution level of task
nohup Run a command immune to hangups, with output to a
non-tty
nslookup Deprecated. Use dig instead
passwd Change user password
perl Practical extraction and report language
pg Browse pagewise through text files
pr Convert text files for printing
pstree Display a tree of processes
python Interpreted, interactive, O-O programming language
rcs Revision control system
renice Alter priority of running processes
rmdir Remove empty directories
rm Remove files or directories
scp Secure copy
script Make a typescript of a terminal session
sftp Secure file transfer program
sort Sort lines of text files
ssh RemoteHost Secure remote login
sudo cmd Execute command as Superuser (requires a password)
sync Flush filesystem buffers
tail file View last lines of a file
tracepath Trace path to a network host discovering MTU along this
path
traceroute RemoteHost Find the route to RemoteHost
uncompress expand compressed files
unzip List, test, and extract compressed files in a ZIP archive
uptime Tell how long a system has been running
vim Text editor (also vi)
vi Text editor (also vim)
wc Print the number of bytes, words, and lines in files
whatis Search the whatis database for complete words
whereis Locate the binary, source, and manual page files for a
command
which Show full path of shell commands
whoami Print effective userid
who Show who is logged on
whois Search the WHOIS database
w Show who is logged on and what they are doing
zip Package and compress files
Heading
keyboard
definition key
key definition
Term . . . . . . . . . . . . . . . . . . . Glossary definition
command options description
<Super>: command # Superusr command
/home/joe user: command # User level command
The Filesystem
/ Root directory
. Current directory
.. Parent directory
Home directory
user Home directory
* Wild card: Match any sequence of characters
? Wild card: Match any single character
ls [D] List the contents of the working directory or directory D
ls -l List the contents of the working directory in long format
ln [opts] Existing New Create a link from New to Existing
cd Change working directory to home directory
cd .. Change working directory up one level
cd pathname Change working directory to pathname
pwd Path to the working directory
cp A B Create a copy of A named B
mv A B Move (rename) file A to B
mkdir A Make a directory named A
rm A Remove file A
rm -r * Remove (recursively) all files in working directory
rmdir D Remove directory D
du Report disk space used in the current directory and all
subdirectories
tar xzf Archive.tgz Dir Extract the compressed tar file into the working directory.
tar tzf Archive.tgz Dir List the contents of the tar file.
tar xf Archive.tgz FileofInterest List the contents of the tar file.
Filesystem Management
du
df
dd
fdisk
mount
sync
umount
mkfs
mkswap
swapon
Printing
lp file System V print command
lpr [-Pprinter] file Print file using printer. See /etc/printcap for list of print-
ers.
lp -Pprinter file Print file using printer
lpr -Pprinter file Print file using printer
lpq [-Pprinter] Check the print queue
lpstat System V: Check print queue
lprm [-Pprinter] job# Remove job from printer queue
cancel job System V: Remove job from print queue
Networking Terms
TCP/IP Transmission Control Protocol / Internet Protocol
udp Best effort packet delivery protocol
tcp Reliable byte stream protocol
rpc Remote procedure call
ARP Address Resolution Protocol
route a network route to another machine
host Any machine on the network
client The host that wants data or a service
server The host that provides data or a service
Email
.forward File in user’s home directory containing mail forward-
ing address
mail user[@RemoteHost] [¡ file ] Mail user agent
pine Mail user agent
elm Mail user agent
mutt Mail user agent
System Information:
Superuser/Root:
su [user] Switch to different user (user must be in /etc/passwd
file)
sudo command Execute command as root (User must be in
/etc/sudoers file)
chown owner : group file Change file/directory ownership
halt This and the next two commands reboot the system
(must be superuser)
reboot
shutdown
Ctrl-Alt-Delete Reboot the sytem
TCP/IP Diagnostics:
Some of these commands may require Superuser priviledges.
/etc/hosts Static table lookup for host names.
/etc/resolv.conf Static table with name of the DNS
/etc/services Internet network services list.
hostname -f Set or show the system’s host name
ifconfig Display or configure local TCP/IP network interface con-
figuration
ping RemoteHost Send a “ping” to a remote host to check connectivity
traceroute RemoteHost Print the route packets take to network host
ipmaddr
iptunnel
arp Display or modify IP-to-Physical address translation ta-
bles used by ARP
rarp
route Print out the local routing table (check /sbin/route)
dig RemoteHost Send domain name query to DNS
nslookup RemoteHost Send domain name query to DNS
tcpdump -i ethX Listen to network traffic on ethX
ethereal Capture and analyze network traffic
netstat Display protocol statistics
netwatch Monitor network connections
nmap Network exploration and security monitoring
whois Client for the whois directory service
System
su user Switch user (requires a password)
sudo cmd Execute command as Superuser (requires a password)
chown user:group file Change file ownership (must be Superuser)
df Report free space remaining in the file system
halt System shutdown
reboot System reboot
Ctl-Alt-Del System reboot
[1] Welsh, Dalheimer, and Kaufman, Running Linux, 3rd Edition. O’Reily & Associates, 1999.
[2] Ellen Siever, Linux in a Nutshell, 3rd Edition. O’Reilly & Associates, 2000.