UNIX Basics
UNIX Basics
Session Contents
History of Unix
Flavors of Unix
Applications of UNIX
Unix Features
Unix Architecture
Relationship :Kernel, Shell, User Programs
Various shells
About vi editor
Unix Commands
Shell Scripting
Sed ( Stream Editor) , Awk programming .
UNIX Introduction
Developed in 1969 by Ken thompson
Popular OS, available from micro to mainframe
Available for scientific as well as commercial use
History of Unix
Originator : Ken Thompson
Redesigned MULTICS SYSTEM and evolved early
version of UNIX
Developed on PDP-7 machine
1971 was written in B language
1973 rewrote the UNIX OS in C
1981 commercial version of UNIX released
Applications of UNIX
Business environment
Word Processing
Financial Accounting
Database management
Communication
Graphics
Software development
Office automation
Academic and scientific environment
Operating system research
Prime operating system for conducting research work
Flavors of Unix:
UNIX is a registered trademark of The Open Group.
FREENIX is a trademark of Applied Digital Arts.
Linux is a Registered Trademark of Linus Torvalds.
UnixWare and Open Server are trademarks of Santa Cruz
Operation.
Tru64 is a trademark of Compaq.
AIX is a trademark of International Business Machines
Corporation.
Solaris is a trademark of Sun Microsystems.
NetBSD is a free, highly portable UNIX-like operating
system available for many platforms.
Falvours of Unix:
HP-UX is a trademark of Hewlett-Packard Co.
IRIX is a trademark of Silicon Graphics, Inc.
U/WIN is a trademark of Global Technologies Ltd.,
Inc.
A/UX and Mac OS X are trademarks of Apple
Computer.
Free BSD and BSD/OS are trademarks of BSDi.
Minix is a Unix-like freely distributed operating
system.
Unix Features
Multi User
Multi Tasking
Portability
Security
Modularity
Multi user
Unix Features
server
0 t 1 t
Some tasks are placed in the background while the
user continues to work in the foreground.
A background task is essentially a non - interactive task.
Unix Features
Portability
Ability of the software to operate on any machine
effectively without major changes to the software.
Shell cat ls vi
-------------------------------
---
Transfer
Built-in Commands
of control
Request for
services
$ cat /etc/shells
You can see what shell you are currently using like this:
$ echo $SHELL
File System
Provides a logical method for organising retrieving
and managing information. The structure of the file
system is hierarchial , resembling an inverted tree.
File hierarchy
Configuration
files
Executables
Types of files
Ordinary files
Directory files
Special files (device files)
Character device files
Block device files
FIFO files
File naming conventions
Max 14 characters long
No concept of primary and secondary name
May contain alphabets,dots,digits and underscores
No embedded spaces or tabs
System commands cannot be used
Case sensitive
UNIX directories
Directories : special files containing names of files and
other sub-dirs
Home directory
Directory assigned by super-user in which a user
normally works
Current directory
Directory from which user is currently issues commands
Standard directories of a UNIX
system
/etc - stores system administration utilities
/bin - stores most commonly used UNIX commands
/usr - stores all user home directories and some UNIX
commands
/dev - stores all the device files
/lib - stores library files for C programming
/tmp - used for temporary storage
Files and processes
Everything in UNIX is either a file or a process.
Example:
-rwxrwxrwx A file that everyone can read, write and
execute (and delete).
- rw- --- --- A file that only the owner can read and
write - no-one else can read or write and
no-one has execution rights (e.g. your
mailbox file).
Wildcards
* Match any number of characters
? Match one character
[ba] Match with one of the characters in
the bracket
[a-z] Match with one of the
characters in between given
two, both inclusive.
[!abc] Match character not not appearing in
bracket
Quotes
Quotes Name Meaning
There are three types of quotes :
" Double Quotes "Double Quotes" - Anything enclose in double quotes removed meaning of that characters (except \ and $).
' Single quotes 'Single quotes' - Enclosed in single quotes remains unchanged.
` Back quote
`Back quote` - To execute command
Unix Process Management
A process is program in execution
Starting a process
1)Foreground process
2)Background process
Process Handling
Moving foreground process to background
nohup command
Listing running processes
jobs
ps
Killing processes
Processes Control Commands
command & run command in background
^c kill the job running in the foreground
^z suspend the job running in the
foreground
bg background the suspended job
jobs list current jobs
fg %1 foreground job number 1
kill %1 kill job number 1
ps list current processes
kill 1243 kill process number 1243
I/O Redirection and Pipes
Redirection
Standard input :
Many commands take input from a file and sends output to
a terminal. These commands can also act effectively on a
character stream, without knowing source of the stream.
The default source of this stream is keyboard. This stream
is called the standard input stream.
The shell sets up the connection between command and
the keyboard.
A stream can come from :
The keyboard (default source)
A file (redirection)
Another program (pipeline)
Redirection : standard input.
The shell can reassign the standard input from a file rather
than a keyboard. This connection is set by the shell using
metachatacter ‘<‘.
Eg.
$ wc < infile
Here the shell reassigns the input to the wc (word count)
command to come from a disk file instead of keyboard.
If input is taken from multiple sources, the ‘-’ symbol must
be used to indicate sequence of taking input. Eg.
$ cat – myfile
<indicates first from standard input and then from
‘myfile’>
Redirection : standard output
The standard output stream can also have three possible
destinations :
The terminal ie. User screen (default destination)
File
Input to another program
The default destination can be changed using ‘>’ operator.
Eg. $ wc infile > newfile
Here the results of the wc command will be sent to the disk
file ‘newfile’.
Eg. $ wc infile >> afile
The >> can be used to append the output to the file instead
of overwriting it.
Redirection : standard error
All error messages are written to the standard error stream.
Error messages such as ‘file not found’ are by default
displayed on terminal.
We need to use the ‘2>’ descriptor to set the standard error;
Eg: $ cat nofile 2> errorfile.
Here if the file ‘nofile’ doesn’t exist in the directory then the
error message ‘No such file or directory’ will be written to
the file ‘errorfile’ instead of being displayed on the screen.
The ‘2’ here actually represents the standard error file. In
fact 0 and 1 are file descriptors for input and output
streams but need not be explicitly specified with their
corresponding redirection operators.
Input/ Output Redirection
I/O Abbreviation Description
Stream
Standard stdin Commands receive information from the user via standard
Input
input. By default, standard input is the keyboard.
Standard stdout Commands send non-error output to the user via
Output standard output. By default, standard output is the
terminal (i.e. written to the screen).
Standard stderr Commands send error messages to the user via
Error
standard error. By default, standard error is the terminal.
Simple Redirection
Example Description
cmd1 | cmd2 Pipe stdout from one command to stdin of another.
cmd < file Read stdin from a file.
cmd << text Read stdin until reaching a line identical to text .
cmd > file Redirect stdout to a file. (overwrite if file exists)
cmd >> file Append stdout to a file.
cmd 2>file Redirect stderr to a file. (overwrite if file exists)
cmd 2>>file Append stderr to a file.
Multiple Redirection
Example Description
cmd1 2>&1 | Pipe stdout and stderr from one command to stdin of another.
cmd2
cmd < f1 > f2 Redirect stdin and stdout simultaneously.
cmd > file 2>&1 Redirect both stdout and stderr to a file. (overwrite if file
exists)
cmd >> file Append both stdout and stderr to a file.
2>&1
cmd > f1 2> f2 Redirect stdout to the file f1 and stderr to the file f2 . (overwrite
if the files exist)
cmd >> f1 2>> Append stdout to the file f1 and append stderr to the file f2 .
f2
cmd | tee f1 Redirect stdout to the screen and to the file f1 . (overwrites f1
if it exists)
cmd | tee -a f1 Redirect stdout to the screen and append it to the file f1 .
Grouping command
Example Description
cmd1 ; cmd2 Execute multiple commands on the same line.
{ cmd1 ; cmd2; Execute
} multiple commands as a group in the current shell.
( cmd1 ; cmd2) Execute multiple commands as a group in a subshell.
Environment changes and defined variables will not persist
outside the subshell.
cmd1 && cmd2 Execute cmd1 . Execute cmd2 only if cmd1 succeeds. && is
called the AND operator.
cmd1 || cmd2 Execute cmd1 . Execute cmd2 only if cmd1 fails. || is called the
OR operator
pipe – output of one command is supplied as input to
Pipes
another
tee – read standard input & writes to std o/p & the file of
user choice
User and group management
To create a Unix user id following information is required
User Management
1. User Name
2. User Id
3. Group Id
4. Home directory
5. Login shell
User name – must be unique consisting of 2-8 letters
User Management
and numerals
User id – Unique user id ranging from 100 to 60,000.
User ID’s 0-100 reserved for system users
Group id – unique numerical id to which the user
belongs. Ranges from 100-60,000
Home directory – identifies user’s home directory path
Login shell – identifies the user shell
Various shells are:
Bourne shell (sh), korn shell (ksh), C shell (csh), bash shell
(bash)
The user and group information is stored in following files:
User & Group Information
/etc/passwd
/etc/shadow
/etc/groups
vi editor
Operates in two modes
vi mode
Insert mode
Command mode
Line dd
Word dw
Copying is called yanking in vi
Copy and paste text
Yanking Text
Line yy
Character
yl
Putting Text
Put after position or line p
Put before position or line P
Search forward /string
Search for strings
Search backward ?string
The syntax is
:%s/pattern/string/flags
Or
:start line no., end line no. s/pattern/string/flags
flags – g, c
Exit saving changes :wq
Quitting
Quit (unless changes) :q
External Commands :
A separate process is spawned.
Steps followed :
Check if built-in command
Check if absolute path is given
Search in PATH – The environment variable containing a list
of directories
COMMANDS
Simple unix commands
Organizing a directory
File management commands
Security Commands
Status information commands
Working with text
Controlling a running program
Redirection commands
communication commands
Process management commands
Command Substitution
This enables the argument of one command to be
obtained from the output of another command.
Eg.
$ echo “Today is date”
Output will be : today is date
ls – directory listing
-a list all entries including those beginning with .
-l long listing
cat – concatenate and display files
Basic Unix
-b number
Commands
the lines Contd.
as in –n but omit numbers for blank line
-s silent about non-existent files
cat <filename>
find – find files
-name True if pattern matches the current file name
-print causes current path name to be printed
find <pathname> -name <filename> -print
grep – search a file for a pattern
-l print only the name of the file with matching lines
-v print all lines except those that contain the pattern
date – write the date and time
date ‘+%m%d%y’
-u – display the date in GMT
cp – copy files
Basic Unix
-i interactive
copy Commands Contd.
-r copy files and subdirectories
cp <source_filename> <destination_filename>
mv – move files
-i asks for confirmation before moving if file already exists
-f move without prompting
rm – remove files
Same options as cp/mv
who – who is on the system
-m – output info about current terminal
-q – display only names and number of users currently logged in
whoami – display the effective current username
pwd – print working directory
Basic Unix Commands Contd.
wc – line, word and character count in a file
-l – count number of lines
-w – count number of words
paste
-d – delimiter character
-s – concatenate each separate line in a file into a single line
paste <first filename> <second filename> > <Out_filename>
tr – translate characters
tr ‘[a-z]’ ‘[A-Z]’ < <input_filename>
shift
Hard Links
Can cross file systems
Not for directories
Syntax: ln filename linkname
Symbolic Links
Can cross file systems
Also for directories
Syntax: ln –s filename linkname
Other Useful Commands
quota
df
du
compress
gzip
file
history
Recalling commands using ‘!’
% !! (recall last command)
% !-3 (recall third most recent command)
% !5 (recall 5th command in list)
% !grep (recall last command starting with grep)
Shell Scripting
Shell Script is series of command written in plain text
What
file. Shellis Shell
script is justScript?
like batch file is MS-DOS but
have more power than the MS-DOS batch file
Example:
grep ‘^name:’ /etc/passwd || useradd name
If the grep command fails then only useradd command will be executed
Or
grep –v ‘^name:’ /etc/passwd && useradd name
Using both && and || in one statement
grep –v ‘^name:’ /etc/passwd && useradd name || \
echo “`date`: useradd failed”
Script Termination
The ‘exit’ statement is used to prematurely terminate a
program.
When this statement is encountered in a script,
execution is halted and control is returned to the
calling program, in most cases the shell.
Argument provided with ‘exit’ is optional.
If you specify an argument, the script will terminate
with a return value of the argument.
If no argument is specified, the value returned will be
zero.
if...else...fi
If given condition is true then command1 is executed
otherwise command2 is executed
Form 1:
Syntax: Form 2:
s1 = s2 True if string s1 = s2
Example :
purge()
{
if [ ! -d $1 ]; then
echo $1: No such directory 1>&2
return
fi
etc...
}
Functions contd.
Within a function the positional parmeters $0, $1, etc. are the
arguments to the function
Within a function use return instead of exit.
Functions are good for encapsulations. You can pipe, redirect
input, etc. to functions
eg:
# take standard input (or a specified file) and do it.
if [ "$1" != "" ]; then
cat $1 | do_file
else
do_file
fi
I/O redirection
Redirection simply means capturing output from a file,
program, command or script and sending it as input to
another file, command or script
Sample Code:
exec 6<&0 #Link file descriptor #6 with stdin
exec <data-file #stdin replaced by data-file
read a1
echo $a1
exec 0<&6 6<&- #Restores stdin and closes fd #6 to free
#it for use with other process
I/O redirection contd…
Redirecting stdout using exec
Sample Code:
LOGFILE=logfile.txt
exec 6>&1 #Link file descriptor #6 with stdout
exec >$LOGFILE #stdout replaced by data-file
echo “Logfile:”
date
Format true if
(( _num1_ == _num2_ )) numbers equal
(( _num1_ != _num2_ )) numbers not equal
(( _num1_ < _num2_ ))
(( _num1_ > _num2_ ))
(( _num1_ <= _num2_ ))
(( _num1_ >= _num2_ ))
Conditional Statements
Strings
Format true if
[[ _num1_ == _num2_ ]] strings equal
[[ _num1_ != _num2_ ]] strings not equal
[[ _num1_ < _num2_ ]]
[[ _num1_ > _num2_ ]]
[[ _num1_ = _pattern_ ]]
[[ _num1_ != _pattern_ ]]
[[ -z _str_ ]] str is null
[[ -n _str_ ]] str is not null
[ x=y –o k=j ] or in expression
[x=y –a k=j ] and in expression
Flow control statements
If-then
If _expr_ then
_cmd(s)_
elif _expr_
_cmd(s)_
else
_cmd(s)_
fi
Flow control statements contd.
case
case _word_ in
_pattern1_) _cmd(s)_;;
_pattern2_) _cmd(s)_;;
*) break;;
esac
Flow control statements contd.
while
while _expr_
do
_cmd(s)_
done
Flow control statements contd.
for
until _expr_
do
_cmd(s)_
done
Positional Parameter
Program, function or shell $0
Argument 1 through 9 $1 .. $9
nth argument ${n}
Number of positional parameter $#
Every positional parameter $@, $*
Value returned by last executed cmd $?
Pid of shell $$
Pid of last background command $!
Redirections
0 stdin
1 stdout
2 stderr
== Equates
!= Not equal to
awk if condition
General syntax of if condition
Syntx:
if ( condition )
{
Statement 1
Statement 2
Statement N
if condition is TRUE
}
else
{
Statement 1
Statement 2
Statement N
if condition is FALSE
}
Loops in awk
For and while loops are used for looping in awk
Syntax for loop
for (expr1; condition; expr2)
{
Statement 1
Statement 2
Statement N
}
Loops in awk contd…
Syntax while loop
while (condition)
{
statement1
statement2
statementN
Continue as long as given condition is TRUE
}
Thank you