Académique Documents
Professionnel Documents
Culture Documents
VIJAY.CHERUKURI
INFOLOB SOLUTIONS INC
Course Outline
Introduction Logging On and Off Unix File System Structure Dealing with Directories Handling Files
Course Outline
Shell Basics Shell Programming Customisation The Internet And more...
Introduction
Unix: a family of operating systems
Initial version (~1969) DEC PDP-7 Rewritten version (~1972) DEC PDP-11 Currently available on machines ranging from notebook PCs to Cray supercomputers
Uses
From embedded control systems (Boeing 777) to weather forecasting
History
The Multics Project
A computer utility Funded by (D)ARPA
Bell Labs Involvement Bell Labs Withdrawal Ritchie & Thompsons Unics
Flavours of Unix
AT&T
Early versions numbered V1, V2 etc. Last being V7
AT&T: System III AT&T: System V UCB: BSD Releases System V release 4
Unix Standards
Theres One for Everybody! System V release 4 (USL)
SVID the System V Interface Definition
IEEE Posix
A series of emerging standards Adopted as a FIPS (Federal Information Processing Standard)
X/Open
Unix Availability
IBM compatibles
Linux FreeBSD386 Solarisx86 SCO Unix
Apple Macintosh
AUX Linux
Unix Availability
Workstations
Sun SPARC
Solaris Linux
Digital Alpha
Digital Unix Linux
Supercomputer
Cray UniCOS
Features of Unix
A multiuser system
Each user has his/her own username or id Many users may be logged on simultaneously Access to files and programs is based on username
Software Availability
You name it weve got it! Programming Languages Text Editors Databases Document Preparation The Net And much, much more
Logging On
Users must identify themselves to the system this is called logging on At the login: prompt enter your id then press Enter (or return) At the password: prompt enter your password note that you cannot see what you are typing Change your password with the passwd (note spelling) command
Logging Off
Disconnecting from the system is called logging off Varies from system to system exit logout ^D
Tabs and spaces (aka whitespace) separate command and arguments Quoting arguments
try echo Im a * - a real * and echo Im a * - a real * The * character has a special meaning which is ignored if it is inside quotes
A Sample Tree
Details will differ from system to system
/ usr smith .login jones ls test.c bin (root) etc fstab
vi passwd
Special Names
Two special entries in very directory Created and deleted automatically . the directory itself
cd ./abc is equivalent to cd abc
This tilde expansion is a feature of the shell . and .. a part of the Unix file system Not all shells support tilde expansion
Manipulating Files
Files are usually created by editors, compilers etc. rm removes files (and directories) cp copies files (and directories) mv moves (renames) files (and directories) ls lists files (not the contents of files) cat displays (con)cat(enates) files
The Shell
The shell is equivalent to COMMAND.COM on DOS On other systems known as the command processor Several alternative shells Most of what is considered the Unix interface is really the shell interface
Shell Flavours
sh the Bourne shell (after its creator): the basic, no-frills shell ksh the Korn Shell: sh plus visual editing csh the C-shell: introduced C-style programming features tcsh: csh plus visual editing bash the Bourne Again SHell: sh plus visual editing
Shell Basics
Shells provide:
Multiple commands on a single line Redirection of input and output Expansion of wildcard filenames Background execution Pipelines Script-programming facility
Wildcard Expressions
We often wish to apply a command to a selection of files or directories The shell wildcard (often known as globbing) feature allows this ls *.c
lists all files whose names end in .c Note that on Unix a . is just another filename character
Wildcard Expressions
When we type in a wildcard expression it is expanded by the shell before the command runs If we type is ls *.c and the working directory contains prog1.c, abc.c and xyz.c then the actual command is
ls abc.c prog1.c xyz.c The wildcard expression has been expanded in place
Wildcard Characters
? matches any character * matches any number of characters [abc] matches any of the characters in the brackets [!abc] matches anything except the characters in the brackets [a-z] matches the range of characters in the brackets
Wildcard Examples
abc?def
matches abcXdef, abc.def, abc3def but not abcdef
abc*
matches abc. abcd, abcdef, abc.another.part
*.*
matches any name with a . Note that this is not the same as DOS
Wildcard Examples
*
matches any name (except a name beginning with a .)
[abc]def
matches adef, bdef and cdef
[a-z]*
matches any name beginning with a lower-case letter
Wildcard Examples
[a-zA-Z]*
any name beginning with an alphabetic character
[!a-zA-Z]*
any name beginning with a non-alphabetic character
[a-z]*[!A-Z]
any name beginning with a lower-case letter and ending with anything except an uppercase letter
ls abc*def
the same
Redirection of I/O
Every program run under Unix is provided with three I/O streams stdin, stdout and stderr
stdin stdout Program stderr
Redirection of I/O
Shell allows any or all of these streams to be diverted prog >file1 sends stdout to file1 prog >>file1 appends stdout to file1 prog 2>file2 sends stderr to file2 prog <file3 takes stdin from file3
Redirection of I/O
Shell also allows chaining of commands together in a pipeline ls > temp; sort < temp >sorted; rm temp
Works, but requires temporary intermediate file, which must be manually removed
ls | sort >sorted
No intermediate file, processes run in parallel
Job Control
Normally the shell waits for a command to complete before prompting for another command Can run a job in the background and not wait for it gcc -o bigprog bigprog.c&
Job Control
Some shells (not Bourne) allow the user to interrupt a running program Use ^Z while the program is running Suspends the job Can resume the job several ways
fg %1 bg %1
Filters
A filter is a command which reads from stdin performs some processing and write to stdout Unixs pipe feature allows us to create pipelines of filters more sort head tail
Access Control
As Unix is a multiuser system some form of access control is essential Unix divides the user community into three categories:
the owner of a file or directory the owners group everybody else
Each file/directory has nine protection bits grouped into three groups
File Permissions
Unix provides three distinct permissions for files:
read permission to examine the contents of a file write permission to alter the contents of a file execute permission to run a file as a program or shell script
Directory Permissions
The same permissions apply to directories, but with different meanings:
read permission to look at the contents of the directory, i.e. to see file names write permission to create or delete files within the directory execute permission to access the directory. Note that read is needed to do filename expansion
Listing Permissions
the -l (long) argument to the ls command lists permissions
-rw-rw-rw- 1 smith comp Jan 20 1:24 file1 a file with read and write for the owner, group and world drwxr-xr-x 1 jones staff Jun 14 8:29 dir1 a directory with read/write/execute for the owner, read/execute for group and world
chmod g=rx
Set group permission to read/write
chmod u+rwx
Add read/write/execute for user (owner)
chmod a+rx
Add read/execute for all (user, group and other)
Default Permissions
Every time a directory or file is created it must immediately have some permissions The umask instruction sets this default umask ddd
ddd is a three digit octal number The default permissions are 777 the umask value
The SuperUser
Every Unix system has at least on userid which is special This is referred to as root although the name may be different root has a user number (in the /etc/passwd file) of 0 root may access any files or directories, whatever their protection bits
Trusted Software
Consider the mail system Each user wants to be able to send mail to any other user No user wants any other user to be able to read his/her mail How can we construct a protection mechanism to allow this?
Creating Files
Most human-readable files on Unix are created with a text editor Unix has many, many different editors ed a very old line-oriented editor ex an enhanced version of ed vi the most ``popular editor a Visual Interface to ex
Editors
emacs full-screen, fully-extensible editor created in the MIT AI Labs pico the pine editor joe Joes Own Editor jove Jonathans Own Version of Emacs And doubtless many others Choose one you like, but learn vi
The vi Editor
Created by Bill Joy at UCB Visual Interface to the ex line editor Holds file being edited as an internal buffer Screen acts as a window onto the buffer Operates in two basic modes
Command mode Insert mode
Starting vi
vi
Starts vi with an empty buffer
vi file
Starts vi opens file for editing
vi +n file
Starts vi opens file at line n
vi +/pattern file
Starts vi opens file at the first line matching pattern
vi command mode
In command mode every character typed is a command You can move about in the buffer Characters/lines can be deleted or moved To enter text shift to insert mode
vi insert mode
In insert mode characters typed are entered into the buffer Shift from command to insert move using:
i insert text before cursor a append text after cursor
vi more movement
nG Go to line n and centre it in the screen /textCR Find text (forward search) ?textCR Find text (backward search) n Find next occurrence of text (same direction) N Find next occurrence of text (opposite direction) See Quick Reference Sheet for more
vi complex commands
Typing the : character in command mode causes a prompt to appear at the bottom of the screen ex commands can be typed here :q
quit vi will complain if there are unsaved changes
:q! or ZZ
quit and lose any unsaved changes
:w filename
write the buffer to named file
:w
rewrite the buffer to an already named file
Special Files
Unix treats every device as a file Special files can refer to
floppy disk CD-ROM hard disk partitions
More on Filesystems
Unix stores files in filesystems A filesystem lives in a hard disk partition, on a floppy or on a CD-ROM or on a networked computer A filesystem is created using a special command, typically newfs or something similar Before a filesystem can be used it must be mounted
Mounting Filesystems
Only root may mount a filesystem The mount command requires three pieces of information
The special file which refers to the device where the filesystem lives The type of filesystem which will be found there The place to make it appear in the filesystem, the mount point
Mounting Filesystems
Assuming: /dev/fd0 refers to a floppy drive There is a DOS formatted disk in the drive There already exists a directory called /mnt/floppy The command (Linux version)
mount -t
Unmounting Filesystems
The umount command is required to un-mount a filesystem Note the filesystem must not be busy
No files open No users with any directory in the filesystem as their current working directory
Examples:
Which shell? Which editor? Which mailer?
Customising Logging In
The login program runs as root After you supply userid and password it:
Switches userid to your userid Runs the shell configured for you in the system password file, which
Sources the system login file Sources your personal login file Displays the prompt
Will be sourced every time you log in Can set up your environment to your own particular requirements
Shell Programming
Each shell defines a simple language While many shell features can be used interactively they find greater utility when used in shell scripts Using shell scripts you can create new commands A shell script is simply a text (ASCII) file containing shell commands
scriptname
Also runs a separate shell to run the script
Script basics
Comments
A shell script is a program Programs should be commented Anything after a # character on a line is ignored by the shell
Examples:
# This whole line is a comment ls -lsa $1 # List the specified directory
#!/bin/cat
Cat the rest of this script (Note that the program doesnt have to be a shell)
#!/bin/csh -f
Invoke the C-shell with the -f argument on this script
Positional Parameters
You can pass parameters to scripts which can be referred to by position within the script myscript first second third If myscript contains the line
echo P1 = $1, P2 = $2, P3 = $3
The shell substitutes the values of the positional parameters before running the command line
Environment Variables
Used for local storage in shell scripts Also used for setting default options for various packages Value established with the set command
set NAME=value NAME=value set NAME set
Testing Conditions
The if command is built in to the shell(s) Usage: if condition1 then commands1 [elif condition2 then commands2] . [else commands3]
fi
Interactive Input
The read command allows input to be taken interactively Usage: read var1 [var2...] Reads one line of input Assigns each input word to successive variable Residue goes to last named variable
Files as links
Unix also allows creation of a link to a file A link is essentially a pseudonym Can view as a pointer to a file Two types of link
hard symbolic or soft
Hard links
A hard link is a directory entry which points to the disk space of another file It is like another name for a file There is only a single copy of the file on disk A file may have numerous links A link may only be to a file on the same file system Changing either name has no side effects
Symbolic Links
A symbolic link is a directory entry which contains the ASCII text string of the pathname of another file or directory It is like a pointer to the other file Changing the name of the pointed-at file will break the link
Patterns
Many Unix tools use the concept of a pattern matching Similar to, but not exactly the same as, the wildcard or glob patterns Examples:
editors grep sed awk
Pattern Basics
A pattern matching string is called a regular expression
. (dot, period) match any single character (except newline) * (star, asterisk) match any number (including zero) of precedingcharacter ^ (caret) match start of line $ (dollar) match end of line
Useful Commands
Among the many Unix commands a few stand out as being particularly essential These include
grep find sed tar compress
All search files for strings which match specified patterns grep ^From: Deryk Mail/*
More on grep
greps behaviour is modifiable via command line options
-c display only count of matching lines -i ignore case when matching -l display only names of files with matching lines -n display line numbers -v display only non-matching lines
grep examples
grep -c t687v1 /etc/passwd
display count of users on this course
Using find
display names of all files in my hierarchy whose names end in .c note quotes
An Editor as filter
The sed (stream editor) acts as a filter Reads a line from stdin or specified file(s) Applies any commands which match Writes line to stdout Command set is drawn from the original ed editor
Using sed
sed [options] command [file(s)] Options:
-n only output lines as specified by printing commands -e cmd specify a command (only needed to specify more than one) -f file file contains editing commands
Commands in sed
Commands have the general form
[address][,address][!]command[arguments]
Addressing:
if no addresses command is applied to all input lines if one address apply to all matching lines if two addresses apply to every line beginning with first and ending with last address! apply to all non-matching lines
/^$/d
delete every empty line
/^[ ]*$/d
delete every line consisting of nothing but whitespace
/^begin/,/^end/p
print lines from begin to end
Using tar
Format:
tar [options] files Functions:
c r t x create new archive append files to archive list contents of archive (or files if specified) extract files from archive
tar tf test.tar
list contents of test.tar
Compressing archives
Whereas pkzip compresses and archives, on Unix use a pipeline:
tar cvf - |compress >test.tar.Z tar cvf - |gzip >test.tar.gz
Internet
TCP/IP suite largely developed on Unix telnet, ftp, mail
Journals
Several magazines devoted to Unix
Usenet News
Many newsgroups devoted to Unix in (nearly) all its many flavours