Using Unix in a Networked Environment

Worthwhile Reading

Abrahams, Paul W., and Bruce A. Larson,
Unix for the Impatient,
Reading, MA: Addison-Wesley Publishing Company 1996.
ISBN: 0-201-82376-4.

Hahn, Harley,
A Student's Guide to Unix,
New York: McGraw Hill, 1996.
ISBN: 0-07-025492-3.

Nemeth, system administration,

On-line manual pages

Window-oriented manual collection
Book Reader, Answer Book, Info, etc.

History of Unix

1969 Ken Thompson develops first Unix
ARPANET formed
1973 Xerox Alto
1977 Apple II, Commodore, Tandy TRS-80
1979 USENET begins
1981 IBM PC & MS/DOS
1982 Sun founded
Ethernet goes commercial
1984 AT&T divestiture
1986 HP PA-RISC
1989 System V Release 4.0 introduced
Sun SPARC
1990 IBM PowerRISC
1992 DEC Alpha
1993 Intel Pentium
1994 Power PC
Novell buys Unix International

Structure of Unix

APPLICATIONS
system call interface
KERNEL
file system interface
FILE SYSTEM
device driver interface
HARDWARE

Unix Applications

Command interpreters
C shell
Bourne shell

Files and directory manipulation
cd
mkdir
mv
cp
ls

Text editing
vi
emacs
pico

Mail
Mail
mail
pine

Software development
cc
lint
make

Nifty utilities
egrep
find
awk
sed

Graphic applications
X window system

Networking
rlogin
ftp
archie
netscape

Unix kernel services

File Services
Directories
Unstructured files
Devices
Mounting disks

Job control
Creation and termination
Memory management
Interprocess communication

Network services
Internet connectivity
Protocols
Networked file systems

UNIX Variations

BSD 4.3 -- UC-Berkeley
System V Release 4 -- AT&T

AIX -- IBM
A/UX -- Apple
IRIX -- Silicon Graphics
HP/UX -- Hewlett-Packard
NextStep -- Next, Inc.
Open Desktop -- Santa Cruz Operation
OSF/1 -- Open Software Foundation
Solaris -- SunSoft
SunOS -- SunSoft
UnixWare -- Novell
Digital Unix -- DEC

NOT "real" UNIX
Windows NT
OS/2
Open VMS


Spec 1170

If it satisfies Spec 1170,
it can be called Unix.

X/Open
Consortium of major Unix vendors and user organization
Controller of Spec 1170
Owner of the Unix trademark

OSF/Motif/CDE

Widgets and style
"look and feel"

3-D look derived from
Microsoft Presentation Manager
Microsoft Windows
Motif screen with buttons

COSE

Common Desktop Environment

Supported by
HP
IBM
Santa Cruz Operation
Sun Microsystems
Novell
Digital
...

Window manager
Motif with some support for OpenLook

Front panel
Based on HP's Visual User Environment

Application Help system
Based on SGML - Standard Generalized Markup Language
Support of present man pages

Personal productivity tools
Mailer
Text editor
etc.

Unix shell

Unix command interpreter
Reads user commands from the terminal
Creates processes to execute commands
Sets up I/O redirection
Controls terminal
Common shells
csh C shell
sh Bourne shell
ksh Korn shell

Starting Unix

login: user-id

password: password



And...
in the X-Window System does a lot more

Upper and lower case matter!

A ROSE is not a Rose is not a rose.

Passwords

To change
passwd
Encrypted and usually stored in /etc/passwd or /etc/shadow
Rules:
Do:
Don't:

A few easy commands

date
Show date and time

cal mm yyyy
Display calendar

hostname
Display name of workstation

whoami
Display your login name

echo "hi there"
Echo message to screen

uptime
Display current system status

uname
Displays name of current Unix system

Unix command format

command options files [RETURN]
separated by white space (spaces, tabs)

command
Required
Program to be executed
Executable file must be in your path

options
Optional
Modify the command
May have their own arguments
Similar to / in MS-DOS commands

files
Usually one
Generally specifies input to the program

Command examples

ls -l pretty_woman
command ls
options -l
files pretty_woman

/usr/ucb/tail +50 .login
command /usr/ucb/tail
options +50
files .login

cc -o myprog -g myprog.c
command cc
options -o myprog
-g
files myprog.c

Ending commands

[ENTER] Normally ends a command
\ Continues a long command to another line
; Separates multiple commands on a single line


Command parsing provided curtesy of the Unix shell.

The one command to remember

man command
Display online manual pages for command

man ls
Display online manual page for ls

man -k keyword
Use keyword to find manual page

apropos keyword
Same as man -k keyword

whatis command
Display one line summary for command


man pages are displayed using more:
[SPACE] for next screen
[ENTER] for next line
/pattern move to pattern
q to quit

man 2 kill
Prints manual page for system call kill

Manual page sections
1 Commands
2 System calls
3 Library routines
4 Devices
5 File formats
6 Games
7 Word processing macros
8 System administration programs


whereis command
To find section of man page for command

man example

cp(1)
NAME
cp - copy file data

Syntax
cp [ -f ] [ -i ] [ -p ] file1 file2
cp [ -f ] [ -i ] [ -p ] [ -r ] file... directory
cp [ -f ] [ -i ] [ -p ] [ -r ] directory... directory

Description
The cp command copies file1 onto file2. The mode and owner of file2 are preserved if it already existed; the mode of file1 is used otherwise. Note that the cp command will not copy a file onto itself.

In the second form, one or more files are copied into the directory with their original file names.

In the third form, one or more source directories are copied into the destination directory with their original file names.

Options
-f Forces existing destination pathnames to be removed before copying, without prompting for confirmation. The -i option is ignored if the -f option is specified.
-i Prompts user with the name of file whenever the copy will cause an old file to be overwritten.

A yes answer will cause cp to continue. Any other answer will prevent it from overwriting the file.

-p Preserves (duplicates) in the copies the modification time, access time, file mode, user ID, and group ID as allowed by the permissions of the source files, ignoring the present umask.
-r Copies directories. Entire directory trees, including their subtrees and the individual files they contain, are copied to the specified destination directory. The directory, its subtrees, and the individual files retain their original names. For example, to copy the directory reports, including all of its subtrees and files, into the directory news, enter the following command:

cp -r reports news

See Also
cat(1), pr(1), mv(1)

Unix directory structure



Some important directories

/ root
/usr/users/stigle
or /home/stigle
home directory for Stigleman
each user has one
/usr/bin most common executables
/usr/lib library files
/etc administrative files
/usr/local locally installed files
/usr/local/uncaww for workshop stuff

Absolute and relative directories

Current directory
Each process is connected to a directory

Absolute pathnames
Start with "/"

Relative pathnames
Don't start with "/" .. and .

..
Refers up the tree to parent directory

.
Stays still


cd /usr/tmp/../users/./conley takes you to?

Directory as a tree

Unix directory hierachy


Directory commands

cd
Change directory to home directory

cd path
Change directory

pwd
Print working directory

mkdir newdir
Make a directory

rmdir olddir
Remove an empty directory

Listing files

ls
List files in current directory

ls /usr/users/curry
List files in a particular directory

ls -l
List files in long format

ls -a
List all files, including hidden ones

ls -F
List files, indicating file types (* = executable, / = directory)

ls -R /etc
List files recursively starting with /etc

ls -alR /
List all files for a very, very long time
Type man ls for many more options!

File commands

cp from to
Copy a file
(Can use wildcards * and ?)

mv from to
Move a file

rm filename
Remove (unlink) file
There is no undelete!

touch filename
Create empty file, or update access times if file exists

more filename
Display a file in screen-size pages

cat filename
Display file on screen without pause

cat filename1 filename2
Concatenates files and displays on screen

lpr filename
Print file

diff filename1 filename2
Compare two files

head filename
Show first 10 lines of file

tail filename
Show last 10 lines of file

grep string filename
Search for a string within file

wc filename
Count lines (-l), words (-w), and characters (-c)

ln -s pathname nickname
Give a file or directory another name

Even more file commands

file filename
Guess contents of file

sort filename
Displays sorted file

uniq filename
Removes repeated lines in file

rev filename
Reverses order of characters on each line

spell filename
Reports misspelled words in file

cmp filename1 filename2
Compares two files

script filename
Saves record of actions to file

Managing file collections

many to one
tar cvf save.tar ./nsf
Places file(s) of directory nsf into single file save.tar

one to many
tar xvf save.tar
Extracts from tar file

bigger to smaller
compress save.tar
Creates compressed file save.tar.Z

gzip save.tar
Creates save.tar.gz

smaller to bigger
uncompress save.tar.Z
gunzip save.tar.gz
Restores save.tar

Ids

The id is the basis of all protection in Unix.

Users and groups are known by numbers.

In most versions of Unix,
a user may be in several groups.

Unix groups and users


Unix process

Unix process


File Security

Two associations for a file
owner (user)
group

Three types of file accessors
same user
same group
others

Three types of file access
Read Write eXecute

For directories,
Read = list names of files in directory
Write = add, remove files from directory
Execute = access files within the directory
% ls -l
total 1550
-rw-r--r--  1 stigle  16802 Jan 20 17:07 book.reviews
-rwxr-xr-x  1 stigle    331 Feb 16 09:39 bx
drw-r--r--  1 stigle    512 Feb 11 10:12 cartoons
-rw-r-----  1 stigle  29521 Jun  9  1993 email.guide
-rw-------  1 stigle   1366 Feb  8 13:57 forms
-rw-rw----  1 stigle   1418 Jan 24 11:41 forweb
-rw-r--r--  1 stigle  25147 Jan 25 16:07 ftp.faq
drw-------  1 stigle    512 Jan 15 13:16 gopher

Setting file permissions

chmod g+w filename
Let group members write the file

chmod o-r filename
Make file unreadable by others

chmod ugo+r filename
Make file readable by everyone

chmod people+access filename
chmod people-access filename
Add or subtract permissions for file

chmod people=access filename
Set permissions for file

chgrp group filename
Set group id of a file

Advanced File Security

Two types of file capabilities
Set-uid Program executes with powers of file's owner.
Set-gid Program executes with powers of file's group.
These bits have special meaning when given to directories.

One anachronism
Sticky bit

As presented by ls

-rwsr-xr-x 1 brock system
Executes with the power of user brock User brock may also execute the file

-rwxr-sr-x 1 brock uncaww
Executes with the power of group uncaww

drwxrwxrwt 1 brock system
A sticky-bit directory
Any user can creates files here, but you can only delete your own files.

Using octal

File modes
odd bitsusergroupothers
rwxrwxrwx
421421421421
Encoding of the odd bits
set-uid4
set-gid2
sticky1

Testing your octal

Odd-bits set-uid set-gid sticky
User read write execute
Group read write execute
Other read write execute
Octal value (your guess)

Printing

lpr filename
Prints file to line printer.
Don't print PostScript to an ASCII printer!

lpr -Pprinter filename
Prints to specified printer

lpr -#2 filename
Prints 2 copies
lpq -Pprinter

Displays spooled print jobs
lprm -Pprinter job#

Removes job from print queue

Related System V commands


X Window System

Implementation
V operating system of Stanford
W window system of Stanford
X Window System of MIT
Bob Scheifler
1984
First commercial release
Digital Equipment Corporation
January 1986
X11R1September 1987
MIT X ConsortiumJanuary 1988
X11R5September 1991
X11R6May 1994

Architecture of X

client/server applications in X

X managers


C Shell facilites


Re-using commands

command action
!! Re-executes the last command.
!ls Re-executes last command starting with ls.
!15 Re-executes the 15th command of the session.
history Displays most recently typed commands.
set history=50 Remember the last 50 commands!
^pat1^pat2 Edit the last command, replacing "pat1" with "pat2".

Command line editing

Varies wildly on different versions of Unix!
This is for the C-shell under Digital Unix V3.2C.

To complete file names

Cut-and-paste

2 clicks of left button picks up word
3 clicks of left button picks up line 1 click of middle button drops text at prompt

Managing input/output

Standard I/O

standard input
keyboard
standard output
terminal screen
standard error
terminal screen

Rediretion

C shell action
> filename Send standard output to a file.
By default overwrites target file.
>> filename Redirect standard output and append to a file.
< filename Take standard input from a file.
>& filename Redirect standard output and standard error to a file.

Piping

One of the concepts from Unix.

Partially borrowed by MS/DOS. Too bad they couldn't do it right.

operator action
com1 | com2 Connect the standard output of com1 to the standard input of com2.
com1 |& com2 Connect the standard output and standard error of com1 to the standard input of com2.

Unix application philosophy

Design small utilities that make interesting transformations of input to output.

Provide a way to connect these utilities.


Examples of redirection

command action
ls > dir.list Directs output of ls to file dir.list
ls >> dir.list Appends output of ls to file dir.list
tr 'a-z' 'A-Z' < .login tr's standard input comes from the file .login.
ls | grep NSF Directs output of ls to input of grep.
make >& make.log Saves standard output and error to make.log.
who | grep daniels | lpr A three process pipe
tar cf - ./stuff \
| compress \
| rsh penrose "zcat|tar xfv -"
Figure this one out!

Using wildcards in filenames

Frequently used with ls, cd, cp, etc.

pattern match
* Matches zero or more characters
? Matches one character
[ch] Matches characters 'c' or 'h'
[A-Z] Matches any upper case letter
X{a,15} Matches strings "Xa" and "X15"
~brock Expands to brock's home directory
~ Matches your home directory

Examples

ls *.c
Lists all C files within current directory.
ls /users/*/X?[A-Z0-9iou]*
Looks rather useless.

Unix gurus call the use of *, "globbing".


Masking special characters

To prevent the C shell from processing special characters, quote the characters.
quoting action
\c Quote single character c which follows backslash.
'string' Quote all characters between the signel quotes except for !
"string" Quote all characters between double quotes except $, `, !, \, and [CR].
Allows variable, command, and history substitution
set noglob Command to shut off globbing.
unset noglob Turn globbing back on.


Controlling jobs

commands action
cc big.c
^Z
^Z suspends a running job.
bg %cc Restarts C compiler job in background.
cc big.c & Runs C compiler as background job.
%cc Brings C compiler back to foreground.
kill %cc Kills C compiler job.
jobs Displays jobs

Making your own commands



alias newname 'command'
From now on, type newname to execute command.


Managing aliases

To list current aliases
alias
To remove an alias
unalias aliasname

Aliases disappear when the shell is closed! To save an alias, put it in the shell initialization file.


Initialization files

Names often start with period. Type "ls -a" to your hidden initialization files.
file purpose
.login login for C shell
.cshrc C shell initialization
.logout logout for C shell
.profile Bourne and Korn shell initialization
.mailrc Berkeley mail
.Xdefaults X windows defaults
.xinitrc X start up program
.newsrc news file
.emacs emacs macros

Environment Variables

Passed by shell to programs you execute.

printenv
Lists environment variables in the C shell.
printenv VARIABLE
Lists value of a single variable.
setenv VARIABLE value
Set or change environment value.
unsetenv VARIABLE
Remove variable.
man program
Find which environment variables a program uses

Common environment variables

name value usual meaning
EDITOR filename Default text editor
DISPLAY host:display.screen Host, display, and screen for X Window display
PATH dir1:dir2:... Directories searched for executable programs.
List of pathnames separated by colons.
PRINTER queue Default printer
TERM terminal brand Type of terminal you are using.
TERMCAP very weird stuff Characters to control the terminal

C shell variables

set
List values of all current variables.
echo $var
Display value of a single variable.
set var = value
Set or change the value of variable.
set var
Turn on a toggle variable.
unset var
Undefine a variable.
set var = `command`
Set variable to value printed to standard output by executing a command.

Common C shell variables

name value meaning
path (dir1 dir2 ...) Directories to search for commands.
Linked to PATH environment variable
filec Enables filename completion on some versions of Unix.
history number Set number of previous commands to save for re-execution.
ignoreeof Prevents shell from accidently being killed by a ^D.
prompt "string" Set shell prompt.
savehist number Number of items to be saved from one login session to another.
Commands saved in ~./history

Customizing C Shell

C shell files can

To test an initialization file type "source pathname".


Making your own commands

Frequent, repetitive, and boring tasks should be done with shell scripts.

Format of the shell script

C shell
#! /usr/bin/csh -f
commands...
#comments
Bourne shell
#! /bin/sh
commands...
PERL
#! /usr/local/bin/perl
neat PERL stuff

After saving a shell script make it executable by typing "chmod ugo+x script".


Easy shell scripts

Nothing interesting ....

#! /usr/bin/csh -f
# hello world script
echo "Hello world\!"

Reading command line arguments

#! /usr/bin/csh -f
# Print GIF file to PostScript printer
giftopnm ${1} \
     | pnmtops -center -scale 2 \
     | ps -Prbh013

A little testing

#! /usr/bin/csh -f
if ( -f userids ) then
     grep ${1} userids
else
     echo "file userids is missing"
endif

SQRT the really hard way

#! /bin/csh -f
# calculate square root
if ( ${#argv} < 1 ) then
  /usr/bin/echo "You forgot the number:  \c" 
  set num = "$<"
else
  set num  = "${argv[1]}"
endif
set numok = `expr "${num}" : '^[ ]*[0-9][0-9]*[ ]*$'`
if ( ! ${numok} ) then
  echo "Can't compute the sqrt of ${num}\!"
  exit 1
endif
@ num = ${num}
@ sqrt =  0
while ( (${sqrt} + 1) * (${sqrt} + 1) <= ${num} )
  @ sqrt = ${sqrt} + 1
end
echo "floor(sqrt(${num})) = ${sqrt}"
exit 0


Press here to retrieve a copy of this fine program.

Useful programs for shell programmers

cut
Extracts fields and characters from lines of input files
finger | cut -c10-35
Displays the "full name" of users.
tr
Copies standard input to standard output while it translates characters
tr A-Z a-z < lorentz.tex
Displays a file in lower case
sed and awk
Very powerful string processors
sed -e "s/HOST/$host/g"
Replaces HOST with the host name
head
Prints the first lines of a file
man sed | head -20
Displays the first twenty lines of a man page
tail
Prints the last files of a file
man sed | tail -20
Displays the last twenty lines of a man page
finger | tail +2 | cut -c10-35
Really displays the "full name"
dirname
Finds the directory part of a pathname
dirname /tmp/myprog.c
Returns "/tmp"
basename
Removes the directory part of a pathname along with unwanted suffixes basename /tmp/myprog.c .c
Returns "myprog"
expr
Arithmetic expression evaluation and regular expression matching
expr " 0# A" : '.*\([A-Za-z]\).*'
Returns "A"
uname
Displays type of Unix system
hostname
Displays name of host
getopts
For sophisticated processing of options given as arguments to the script. Read the man page!

finding files

Command format

Simple example

find . -type f -size +200 -print
To display names of all files in current directory and all subdirectories larger than 102,400 characters (200 blocks).

Some find tests

test meaning
-name file Name of file (can glob)
-user login-in Owner of file
-type codes Type of file
-atime days Access time
-size blocks Size of file in 512 byte blocks
-print Print name of file
-exec command \; Command execution result
-ok command \; Command execution, but ask first
-perm octal File permissions

find examples

Find directories in /tmp accessed this week
find /tmp -type d -atime -7 -print
Remove backup files created by emacs
find . -type f -name "*~" -exec rm {} \;
Find large files no one is using
find . -type f -size +500 -atime +30 -print
Find files and directories writable by everyone
find . -perm -002 -print

find operators

Usual logical operators

and
case1 case2
or
case1 -o case2
not
\! case
grouping
\( case \)

Highfalutin examples

Run "ls -lg" on all files or directories whose names start with "nsf". find . -name "nsf*" \
\( -type d -o -type f \) \
-exec ls -lg {} \;
Remove all files owned by melville which do not contain the word "Moby". find . -type f -user melville \
\! -exec grep -s Moby {} \; \
-exec rm {} \;

Regular expressions

Invented by linguists and mathematicians. Beloved by computer scientists, particularly the theoretic ones

A way to specify searches such as "Match a string that consists of a bunch of a's followed by either iou or IOU.

Regular expressions are used in

Unfortunately, the syntax varies

egrep -- extended grep

Command format

Example atomic elements

a
Matches character "a"
.
Matches any single character
[iou]
Matches any of three characters
[0-9]
Matches any digit
^
Matches beginning of line
$
Matches end of line

Example regular-expression operators

(na)*
Matches zero or more consecutive occurrences of "na"
X|Z
Matches "X" or "Z"
s?
Matches an optional "s"

Examples to ponder