Unix, developed in 1969 by Ken Thompson and Dennis Ritchie at AT&T, operates on principles like treating everything as a file and using small, single-purpose programs. The GNU Project, initiated in 1984, aimed to create a free UNIX clone, leading to the development of Linux by Linus Torvalds in 1991, which is a multi-user, multi-tasking operating system. Key features of Linux include a flexible user environment, file access permissions, and various utilities for file management and system operations.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0 ratings0% found this document useful (0 votes)
22 views100 pages
OS Unit-4
Unix, developed in 1969 by Ken Thompson and Dennis Ritchie at AT&T, operates on principles like treating everything as a file and using small, single-purpose programs. The GNU Project, initiated in 1984, aimed to create a free UNIX clone, leading to the development of Linux by Linus Torvalds in 1991, which is a multi-user, multi-tasking operating system. Key features of Linux include a flexible user environment, file access permissions, and various utilities for file management and system operations.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 100
4 LINUXUNIX History
Unix was originally developed for internal use at AT&T by Ken
Thompson and Dennis Ritchie.
First version created in Bell Labs-1969.
Unix flavors are AIX from IBM, HP/UX from Hewlett Packard SunOs
from Sun and IRIX from SGIUNIX Principles
= Everything is a file-Including hardware
By treating everything as a file, a consistency emerges. You can secure
access to hardware in the same as you secure access to document
= Configuration data stored in text
Storing Configuration in text allows an administrator to move a
configuration from one machine to another easily.
= Small,single-purpose programs
Unix provides many small utilities that perform one task very well.
"= Avoid captive user Interfaces
Most commands expect their options and arguments to be typed on the
command line when the command is launched.
= Ability to chain programs together to perform complex tasks
A core design of UNIX is that output of one program can be input for
another.GNU Project/GPL
= Gnu project started in 1984
Goal: To create “Free” UNIX clone
= Free Software Foundation
“Free Software” doesn’t refer to the cost of the software, but the
fact that end user has free to modify and change the program.
= GPL-GNU General Public License
Primary License for Open Source software
Encourage free softwareLinux Origins
= Linux Torvalds
Finnish college student in 1991
Created Linux Kernel
= When Linux kernel combined with GNU applications,complete free
UNIX- OS possible.Linux Principles
Fresh implementation of UNIX APIs
Open source development model
Multi-user and Multi-tasking
Linux is a multi-user and multi-tasking operating system. That means
more than one person can be logged on to the same Linux computer at the
same time.
Multitasking, a user can have more than one process at the same time
Supports wide variety of hardware
Supports most piece of modern X86-Compatible PC hardware.
Supports many configuration protocols and configurations
Fully SupportedHardware Specifications
= Pentium-class or better CPU
= 128 MB or more RAM
= 2-6 GB disk space depending on intended use
= Bootable CD-ROM or 3 ¥2” floppy driveOverview of Linux
Components of the Linux User Environment
Local Logins
Device files
Getting Help
Date, Time and Calendar
Virtual ConsolesComponent of the Linux User
Environment
= Kernel
Its jobs is to perform many low-level and system-level functions, to
interpret and send instructions to the system hardware
= Shell
It provides an interface by which the user can communicate with the
kernel.
= Terminal Emulator
It gives the shell a place to accept typed commands to display the results.
=X Window System
It Provides the bitmapped color display and the environment in which
program such as web browser, mail clients can display the window
= Desktop Environment
It is the collection of Software applications with which users can interact
to accomplish their tasks.Local Logins
= Basically user can Login in 2 modes
1. Text-mode login
It nothing but, user switching to runlevel 3 environment
2. Graphical Login
It nothing but, User switching to runlevel 5 environmentDevice Files
= Linux access hardware devices through files.All hardware devices are
treated as “special files”
= Basically there are two types
1. Character devices
2. Block devices
Character devices:
Character devices, such as serial ports and modems, transfer data
one byte at a time.
Block Devices:
Block devices such as hard drives, transfer data in blocks. Block
typically range in size from 512 bytes to 32 KB.Getting Help
= man displays pages from reference manual.
= Manual page contain multiple section
1. User commands
. System calls
3. Library calls
4. Special files
5. File Formats
6. Games
ie
8.
N
. Miscellaneous
Administrative commands
ities
info- Text based help system that organizes its information into
sections.Date Time and Calendar
= Date- display date and time
= Cal-Prints an ASCII character of the current month
cal 8 2005
display calendar of the 8 month of the year 2005.Virtual Consoles
Multiple non-GUI logins are possible through the use of Virtual
consoles.
There are by default 6 available virtual consoles
Virtual console available through Ctrl-Alt-F74 File and Shell BasicsFile Information
= Files names may be upto 255 characters
= File names are case-sensitive.
= Files and directories on Linux system can be named by any combination of
letters, numbers and most punctuation symbols.
= pwd- Displays the absolute path to the current directory
= Location of directory can be specified by two methods
= Absolute pathname :
Absolute pathname starts with /. It is complete road map to a
location.
= Relative Pathname:
Relative pathname do not begin with /. Specifies location
relative to your current working directory.Changing & Listing Directories
= cd -change directories
cd /home/joshua/work : To an absolute path
Listing Directory contents
:Lists the contents of the current directory or a specified
cd.
cd
cd -
Is
Is
Is-a
Is-R
Is -d
: Toa directory one level up
To your home directory
To your previous working directory
directory
slong listing of contents of information in directory
listing of hidden files and directories whose file begin
with a dot.
:recurses through the subdirectory it encounters,listing
the contents too.
lists directory namesSystem Directories
= /bin, /usr/bin : User commands
= /sbin, /usr/sbin fg administrator commands
= /var fs logs,PID files, mail
= /proc $ “virtual window” into the kernel
= /etc Configuration files
= /lib shared libraries
= /dev device files
= /boot Linux kernel and boot files
= /home user’s home directories
= fopt : third party packagesChecking Free Space
= df : Reports filesystem disk space usage in kilobytes, megabyte and
gigabyte
du —h : displays filesystem information in human readable format
= du- Estimated file space usage.
-h : makes the output in “human readable” format
-s : To summarize space in a directoryCopying Files and directories
= cp-copy files and directories
Syntax:
cp __ [options] source file destination file
cp [options] source files destination file
= cp-r: recursive copy
= cp -p: Preserve time and date information when making a copy
= cp-f : forceful copy of file to destination fileMoving and Removing files and directories
= mv -move and/or rename files and directories
= mv-must always be given at least two arguments.
Syntax:
mv [ options ] source file destination
mv [ options ] source files... destination
= mv and copy functions are identical, the only difference is that cp-
results in matching identical files; with mv, the source disappears
leaving only the destination filesCreating & Removing files and directories
= touch- create empty files or update file timestamps
= mkdir- create a directory
= rmdir- remove an empty directory
= rm - remove files
-I: interactive
recursive
-f :forceTypes of viewing file
cat —contents are displayed sequentially with no break.
less- Displays the contents of a text file one screen at a time
Syntax:
less [options] [filename]
tail - Displays last few lines of a text in a file.
Use —n or — lines to change number of lines displayed.
Syntax:
tail [ options] [ filename ]
Head: Displays first few lines of text in a file.
Syntax:
head [ options ] [ filename ]4 Users and Group InformationUsers
= Every user of the system is assigned a unique User ID
= User names and uids are stored in /etc/passwd
= Users are assigned a home directory and a program that is run when
they login
= Users cannot read, write and execute each other files without
permissionGroups
Users are assigned to groups with unique group ID number ( gid )
gid are stored in /etc/group
Each user is given their own private group. They are also added to
other group to gain additional access.
All user in a group can share files that belong to the group.Root User
Root user is administrative account on Linux system.
Root is sometime called super user.
Root has complete control over the system.
Root has complete control over the system.
When operating as a root, small typo of rm command can irretrievably
delete all the files on the system.
Server programs such as web or print servers typically run as privileged
users, not as root. Because running program in this way limits the
amount of damageUser Information Commands
= whoami:
Find out who you are
= Groups, id:
Use to find out what group you belong to
= Users, who , w:
Find out who is logged in
= Last:
Login/reboot history
= Finger:
User information lookup
= Su: To start a new shell as a different user+} File Access PermissionsLinux File security
= Every file is owned by a user and associated with a group
= Access to a file or directory is determined by the read, write and
execute permission for its user and group ownership and for
“others”
= File permission can be viewed by Is +I
= File type and file access permissions are symbolized by a 10-
character stringUser categories
= File permission file access in three general categories. Each category is
denoted by one symbol
= U- the file’s owner
= G-other users in the file’s group
= O- everyone elseFile Permission Types
= r— Permission to read a file or list or directory contents.
= w- Permission to write or change the file or create and remove files
from the directory
= x- Permission to execute a program
= Each of the standard permission types can be used to a restrict access
for the file’s user, access for the file's group and access for everyone
else.
= A file may be removed by anyone who has write permission to the
directory in which the file resides regardless the ownership or
permission on the file itself.Examining user, group and
other permission
= User Permissions:
Characters 2,3 and 4 in the access mode identify user permission
-rWx: root root 1024 Aug 17:10 README
= Group Permissions
Characters 5,6 and 7 in the access mode identify group permission
----rwx--- 1 student visitor 1024 Aug 18.00 README
= Other Permission:
Character 8,9 and 10 in the access mode identify permission for others
sonnant wx 1 student visitor 1024 Aug 18.10 README
= This file can be read and written and executed by people in visitor.Changing Access Permission
= Each mode can be either be a numerical expression, or can be defined by
combining the letter for who has access to file, an operator for selecting how
the permissions should be changed, and permission for the file or directory.
= Who may be chosen from
u- Users who owns the file
g- Users in the file Group
o- Others users
a- All three category
= Operator may be chosen from Permission may be chosen from
+ add a permission r read
_ Remove a permission w- write
= Assign a permission x- Execute
s- set user ID
te sticky bitChanging Access Permissions
chmod- to change access modes
Syntax:
chmod [ mode ] filename...
Eg:
chmod g+w -bashre
chmod u=rw___bashrc
chmod -R :
This mode traverse an entire directory tree to change the
permission of all its files and directoriesChanging Permissions-Numeric method
= Numeric method uses three-digit mode number
First digit represents owner permission
Second digit represents group permission
Third digit represents other’s permission
Permission are calculated by adding
4- read
2-write
1-execute
Syntax:
chmod [ mode ] filename
Eg:
chmod 644 file :
Read and write permission set for the owner and group; read
only for othersSpecial Permission for Executables
= Apart from three user categories, there is fourth permission category
that sets the special permission
= set-user-ID(suid)
= set-group-ID(sgid)
= There are displayed for “s” for user or group in executable position * x ’+} Linux Filesystemext2/ext3 Filesystem Details
= SuperBlocks:
When an ext2 or ext3 filesystem is created, the filesystem specific
metadata is stored in a superblock. Because this data is critical to the
operations of the filesystem, copies of the filesystem superblock are
also created.
= Dumpe2fs:
It used to view much of the data stored in a filesystem
superblock.
= Inodes:
Inodes act as maps or descriptions to the data contained in the
various filesystem block. While inodes to not store the actual data of a
file,they do not contain information about the file.Links
= Hard Links:
Hard links enable one file to have two or more names. A user can
create a link to a file that he does not own.But that user is still bound
by the information stored in the inode for that file.
Syntax:
In filename [ linkname ]
= Soft ( Symbolic ) links:
Symbolic link stores the name of the file to which it points. If the
referenced file is moved or renamed the symbolic link will point
nowhere.
Syntax:
In -s filename [ linkname ]Mounting Removable device
= Before you can access the data on newly inserted removable media,
the filesystem on the media must first be mounted.
= When using X, inserting a CD into the drive automatically mounts the
CD and bring up a nautilus window.
= We can mount the CD and Floppy drive using the following command
Floppy:
mount —/mnt/floppy
unmount /mnt/floppy
CD-ROM:
mount —/mnt/cdrom
unmount /mnt/cdromLocation Files
= Slocate:
Slocate prints names of files or directories that match a supplied
pattern.
Slocate is more powerful than find. It uses the database instead
of searching in real time.
Syntax:
slocate [ pattern ]
= Find:
Find can also be used to search for files by
type,owner,modification date and many other criteria
Syntax:
Find < dirs> [conditions] [action]Compression Utilities
= gzip, gunzip:
Standard Linux compression utility, Up to 75%
compression of text files.When a filename is compressed with utility
carry the extension .gz. The file compressed by this utility is
uncompressed by gunzip.
= bzip2, bunzip2:
A newer Linux compression utility. File
compressed by this utility carry the extension .bz2 and are
uncompressed with bunzip2. Bzip2 compressed file are smaller in size
than their gzipped file.
= Other utility:
Another utility available in linux is zip, pkzip, winzip. This utility is
compatible in Dos/Window, and is used to compress more than one file
into one file.Creating/Extracting Archive
= Archiving places many file into one target file. It is easier to backup,
store and transfer.
= tar- Standard linux archiving command.
= Creating an archive:
tar -cvf archive_name files...
c-create a new archive
v-produce verbose messages
f-archive_name is name of new file
= Extracting an Archive:
tar —xvf archive_name.tar
x- extract a archive fileCompression Archives
= tar can perform the compression on the fly with either the z or j option
= When creating tar archives, output files are often named with a .tgz
extension.
= Compression switches during creating and extraction
= z for gzip compression
= j for bzip2 compression4 Bash ShellVarieties of Shell
Bash-Bourne Again Shell(bash)
Developed for the GNU Project.
Sh-Bourne Shell
Originally UNIX shell written by Steven Bourne at AT&T
csh-C shell
Written by bill joy at UC Berkeley.C shell was so named because
its scripting language has a syntax similar to the C Programming
language.
ksh -Korn Shell
Written by David Korn of AT&T.
tcsh- Enhanced C shell
Enhanced C shell includes many innovative features such as spell-
checking commands and filenamesShell Variables and Environment
= A variable is a label that has a value, used to configure the shell or
other programs
= Variables are resident in memory. Variable are two types
1. Local variables:
Local variables are used only by the shell.
2. Environment variables:
Environment variables are passed onto another commands
Display variables and values using
set- used to display all variables
env- used to display environment variablesEnvironment Variables
= Shell variables exists only in current shell instance.
= Environment variables passed to subshells environment
= Commonly used Environment variables.
HOME-
PATH-
LANG-
PWD-
USER-
TERM-
SHELL-
DISPLAY-
VISUAL-
EDITOR-
Path to user’s home directory.
Executable search path; A list of directories to look for
programs in
Identification of default language programs should use
User's current working directory.
Username of user
Login terminal type
Path to login shell
X display name
Name of visual editor
Name of default editorBash Commands
which- shows path of executable run when a command is typed
History- It is used to see list of “remembered” commands.
~ - Itis refer to the home directory
Aliases: aliases let you to create shortcuts to commands
alias dir="Is Jaf”
Command Line Expansion:
$- Substitute the value of a variable in a command line
{}-A string is created for every pattern inside the braces regardless if
any file exists
$(_) — Substitute output from a command in a command line
$ ]- Substitute result of arithmetic expression in a command line.
* - Matches any string of characters
? - Matches any one character
[ ] - Matches any characters inside brackets
\ - Used as a last character on line to continue command on next line.Command Editing Tricks
[ TAB ] to complete command lines
[ ctrl -a ] -> moves to beginning of line.
[ ctrl -e ] -> moves cursor to end of line.
[ Esc ] - f -> moves cursor to beginning of next word.
[ Esc ] — b -> moves cursor to beginning of previous or current word.
[ ctrl -k ] -> deletes to end of line.
[ ctrl -u ] -> deletes entire line.
Set —o vi -> to change keybinding to vi-styleStartup Scripts
= Scripts of commands executed at login
Order of Execution
= 1. Login shell: Login shell are first shell started
/etc/profile
/etc/profile.d
~/.bashre
/etc/bashre
= Non-login shells : Non-login shell reference some of the same files,
but note the difference in order.
~/.bashre
/etc/bashre
/etc/profile.d+} Standard I/O and PipesStandard Input and Output
= One of most important features of Linux is the streaming nature of
data as standard input, output and standard error.
= In general, this allows the input from a program to come from any
source, and the output to go to any source.
= Linux provides three I/O channels to processes.
1.Standard input- Keyboard is default
2.Standard output- terminal window is default
3.Standard error- terminal window is default.Redirecting Input and Output
= Standard output of commands, which ordinarily displays on the terminal, can be
redirected into a file or piped into another command.
= Standard error, which also ordinarily displays on the terminal, can be redirected
into a file.
= Standard input, ordinarily coming from the keyboard, can be redirected from a
file.
= Commonly Redirection Operators
= > command > file Directs standard output of command to file
= >>command >> file Appends standard output of command to file.
=< command < file Command receives its input from file.
= 2> command 2> file Error messages from command are directed
to file.
= 2>> command 2>> file Errors messages from command are appended to
file
= | command 1 | command2 -Pipes the standard output of command! into the
standard input of command24 Introduction to String ProcessingString Processing Commands
= We ( word count ): It is used to count lines and characters
= Sort: — Sort is used to sort data. This data can be in a file or the output of
another command.
Syntax:
Sort [options] file(s )
= Uniq:Uniq removes duplicate adjacent lines from a file.
= Cut: Cut is used to cut fields or column of text from a file and display it to
standard output
= Paste: Paste files together
= tr-character translator.Formatting Tools
= expand expand tabs into space
= fmt
= pr
= diff
= aspell
reformat text into paragraphs
reformat text for printing
diff is used to compare the contents of two files for
difference.
Aspell is an interactive spell-checkerString Processing with regular
expression
= Regular expression are pattern matching engine
= Regular expression can be divided into 3 broad categories:
1. Wildcard character stand for another single character
2. Anchor match the beginning or end of a line or word.
3. Modifiers determine the number of the previous character.
= Tools that use regular expression are
1. grep
2. Sed
3. less
4. awkWildcard Characters
= Wildcard characters in regular expression represent some other
character.
= The wild character sequence are:
Represents any single character.
[abc] any single character in the set.
[a-c] any single character in the range.
[ Aabc ] any single character not in the set.
[4a-c] any single character not in the range.Modifiers
= Modifiers determine the number of the previous character.
= Modifiers sequence are
\t+
\?
MIN
\{i\}
\{Li\}
zero or more of the previous character
one or more of the previous character
Zero or one of the previous character
exactly i of the previous character
i or more of the previous character
i to j of the previous characterAnchors
= Anchors match the beginning or end of a line or word.
Anchors sequence are
wn line begins with
$ line ends with
\< word begins with
\> word ends withGrep
General regular expression processor, displays the lines in a file that
match a pattern.
It can also process standard input.
Also used as filter in pipelines
Is | grep.c
Command options used with the grep command includes
-v returns lines that do not contain the pattern
-n precede returned lines with line number
-c only return a count of lines with the matching pattern
-| only return the names of files that have at least one line
containing the pattern
-r perform a recursive search of files, starting with the named
directory.sed
sed- stream Editor
Reads a file or stream of data; writes out the data, performing search
and replace instructions.
Uses regular expression in search string.
Quote search and replace instructions
Sed ‘ s/dog/cat/g * pets
Multiple sed instructions
Sed -e ‘s/ dog / cat /‘-e‘s/hi/lo/' petsawk
Programming language for editing text
Searches a file for lines matching a pattern or pattern
Performs specified actions on matching lines
Search patterns are extended regular expression
Awk programs are data-driven
Awk rules contain a pattern and an action in curly braces.
Pattern { action }
Action is taken on any line matching the pattern4 Process ControlHow Process are created
A process is an executing program with several components and
properties.
Process has many components and properties like exec thread, PID,
priority, memory context, environment, file descriptors, security
credentials.
One process “forks” a child, pointing to the same pages of memory,
and making the area as read only.
Then the child “ execs “ the new command, causing a copy-on-write
fault, thus copying to a new area of memory.
A process can exec, without forking.
The child maintains the process ID of the parentProcess States
Init is the first process started at boot time- always has PID 1
Except init, every process has a parent.
Processes can be both a parent and a child at the same time.
Process can be in one of many states
R- Process is on the run queue
S- Process is not executing and is typically waiting for an event to
occur to wake it up.
T- Process is not executing
D- Process is sleeping and cannot be woken up until an event occurs.
Z- Defunct Process (zomble). Just before a process dies, it notifies its
parent and waits for an
acknowledgment. If it never receives it, its PID is not freed but all
other resources are freed.Sending Signal to Processes
Signals can be specified by their name, such as KILL, or by their
number such as 9.
Kill can send many signals, but processes only respond to the signals
they have been programmed to recognize.
Kill [ -signal ] pid (s )
Kill [ -signal ] Yojob ID
Default signal is TERM
In addition to kill, there is a killall command that can be used to send a
signal to a group of commands such as getty processes.
Kill +I lists all available signals.
Signals can be sent to processes interactively using top.
Ps- displays information about processes on the system.
ps —a Display all processes, not including processes not controlled by a
terminalAltering Process Scheduling Priority
Nice: Nice can be used to run an executable scheduling priority.
With —n option, the process uses default value of 10.
Priority value can range from —20 to 19.
Top: top can be used to display process's scheduling priority, and to
determine which ones are monopolizing system resource
Renice: renice changes the priority of a running process
# is the priority value.
-p only alters priority of the listed process and not any child
process
Once a priority value is raised, a non privileged user cannot lower
it.
-g will alter an entire process group’s priority.Suspending and Running a Process
= Running a process in Foreground and Background:
When a process is started from a terminal's command line, it is running in
the foreground. The process can be stopped, restarted in the background, or
terminated. This is called job control
A background process is child of the processes that spawned it. The
parent process does not wait for the child process to terminate before executing.
When a process is started in background, a new “ sub-shell ” is created.
= Suspending a Process:
Jobs that have started in the foreground can be suspended. They are
Resumed in the background (bg )
Resumed in the foreground (fg )
[ ctrl-z ] sends a signal to the foreground process to
suspendListing and Resuming Suspended
jobs
= Jobs displays all reports running in the background or that are
suspended.
Jobs [ id]
= The number in brackets is a job number, used to kill jobs or bring them
back to the foreground.
= Jobs are referenced by %.
= When a command is suspended or backgrounded, it can be brought
back to the foreground with fg.
= Suspended jobs can be resumed in the background with bg.
fg [ Yojob_number ]
bg [ Y%job_number ]4 Usage of Vi and Vim EditorsStarting vi and vim
= vi: The “visual editor”, the standard Linux and Unix editor
= vim: the “vi improved” editor, standard Linux editor
= To start vi:
If the file exists, the file is opened and the contents are
displayed.
If the file doesn’t exist, vi creates it when the edits are saved for
the first time.
vi filename
= When invoking vi in this way, you actually invoke vim, as vi is an alias
to vim.Modes of vi and vim
The vi editor operator in three modes in three different operation.
The three modes are
1.Command mode
2.Insert mode
3.Ex mode
When you first enter vi, you will be in command mode. This is
considered as “home” mode, the mode to which you will return when
you are otherwise not performing some specific action.
In insert mode, your keystrokes are actually data entered into your
document, rather than commands.
In ex mode, you can enter extended commands. Among the extended
commands are saving, exiting, and search-and-replace commands.Cursor Movement
= Cursor movement command:
left
down
up
right
word ahead
word back
sentence back
sentence forward
paragraph above
Paragraph below
= Arrow keys also work.
waronasrxAzurInsert Mode
= We can enter into insert mode by entering keystroke i.
append after the cursor
insert before the cursor
open a line below
append to end of line
insert at beginning of line
open a line above
orro-wa
To get from insert mode back to command mode, press the < esc > key.Change,Delete and Yank
change delete Yank
Line cc dd yy
Letter d di yl
Word cw dw yw
Paragraph above ef dt yf
Paragraph below o d} y}
Sentence ahead ( a ¥
Sentence behind °) d) y)
Use p of P to put(paste) copied deleted data
= Line oriented data:
Pp puts the data below the current line
P puts the data above the current line
= Character Oriented data:
P puts the data after the cursor
P puts the data before the cursorSearching for text
To search for a string of text, use the / or ?
/text search downward for “text”
?text search upward for “text”
n continue search in the same direction
N continue search in the opposite direction
Undoing Changes:
Undo most recent changes.
undo all changes to the current line, since the cursor
landed on the line.
< ctri-r > redo all last “undone” changes.
ccSaving and Exiting:ex mode
The most important functions of ex mode is save and exit commands. Ex mode is
entered from command mode using colon character.
save changes abandon changes
Exit :wq :q!
Do not exit :w rel
Forcing changes
saving changes
Exit sw!
Do not exit cw!
Other commands:
dtc delete from cursor to the letter c
x delete a character
re replace a character with cSearch and Replace
= Vi and vim perform search and replace, much like the sed command.
Different default addressing rule
No address current line only
1,$ for changes to entire file
-,- +10 from current line(“.“ ) to current line plus 10 lines
("10°")
8,12 changes lines 8 through 12.
= Regular Expression in vi and vim:
Regular expressions operate in less-like search operations
i1, $s /\[Cc]at\> / &and dog /g
This will replace all instances of the word “Cat” or “cat” with the
expression.File & Screen Repositioning
= File Repositioning:
3 G
= 1G
=
=
=
=
go to last line in a file
go to first line in file
go forward one full screen
go back one full screen
go down half a screen
go up half a screen
= Screen Repositioning:
"oH
=M
we
= z
27
go to first line on screen(high)
go to middle line on screen(middle)
go to last line on screen(low)
make current line first line on screen
make current line last line on screen4 bash Shell ScriptingBasics of Scripting
= Ashell script is simply a text file containing commands.
= UNIX users involved with system administration and troubleshooting
often work with shell scripts.
= /etc/profile.d is the system-wide user login scripts which runs whenever
user logins into the scripts.
= Shell Scripting are useful for:
Automating command entry
Performing system administration and troubleshooting
Creating simple applicationsHandling Shell Scripts
= Shell scripts generally contain command per line, but you can have
multiple commands on a line if you separate them with semicolons.
= Line continuation character for bash is \.
Creating shell scripts
Use a text editor such as vi or pico to create a text file containing
commands
Make sure first line contains magic #!, contains name of
shell(interpreter) to be used to parse script.
Making Scripts Executable
After creating scripts, we can save it using text editor.You will
need to change its file permissions in order to make it executable.
chmod a+*x filename.shHandling Input/Output
= Read:
It is used to assign an input value to an shell variable.
Syntax:
read word/character
= Echo:
Echo is used to generate simple output.
Syntax:
echo ‘ Welcome to world of Linux”
= Printf
printf is used to produce formatted output.
Syntax is similar to C printf (). function.
= Exit:
0 for success, 1 to 255 for failure.
shell script set an exit status with the exit command.Conditional Execution
= We can execute command conditionally, depending on the exit status
of another command.
Bk Logical AND
I Logical OR
Rk When executing two commands separated by &&, the latter
command will only run if the former command exists successfully.
ll When executing two commands separated by || the second
command runs successfully if the first command failed.Conditional Execution using
if statement
= Conditional logic statements evaluate test expressions and perform
different actions depending upon the results of the test.
= Basic format of if statement
Syntax:
if condition
then
command (s )
else
Command (s )
fi
Tf the test expression is true then the commands after then are executed,
otherwise the commands after else are executed.Conditional Execution
Using the case Statement
= The case statement provides an alternative method for performing
conditional execution
Syntax:
Case expression in
Pattern 1 )
Statements ; ;
Pattern 2 )
Statements ; ;
#default case action
esac
If the expression matches any one of the pattern then the statements
following the pattern are executedFor-Loop
= The for loop structure provides an method for executing commands
repeatedly for a list of values.
= Syntax:
for variables in list of values
do
commands ...
done
The values are normally strings. Looping continues until the list-of-values
is exhausted.While-loop
= While loop structure provides a useful method for performing a set of
commands while a condition remains true.
= Syntax:
while conditions
do
commands...
donecontinue and break
Continue
Continue stops the current execution of the loop and
reexamines the initial condition possibly restarting the loop.
Break
break stops processing the loop entirely, jumping past
the done statement.
Exit:
Exit exits form the shell script entirely
Positional Parameter
Positional Parameter are special variables that hold the
command-line argument to the script.
$* hold all command-line arguments+} Basic NetworkingNetworking commands
Ping: Ping command is used to test network connectivity and
reliability.
traceroute: Shows network path between local and remote systems.
netstat: Lists network statistics and parameters.
lost is useful for resolving hostnames to IP address.
ig: Dig will resolve hostname
Fwhois: Fetches domain registration codes from InterNIC and domain
registrars
Lftp: Iftp is a useful command-line ftp client with such features as bookmarks
and tab completion.
Wget: It can be used to retrieve a single file via HTTP or FTP.
telnet: It is useful for checking and troubleshooting services.
ssh: It allows remote login and remote command execution via a secure
encrypted connection.
rsync: It is a protocol allows to transfer files using efficient checksum algorithm4 System ToolsTerminal Configuration
The terminal is the window which you interact with the command line.
TERM:
This variable tells the system what terminal type is being used.
Stty:
This utility sets or displays terminal settings.
Reset:
Sometimes the output of a program or command will cause the
terminal to stop displaying correct characters. This can be fixed by using
reset.
eval ‘resize’:
A pseudo-terminal window, such as xterm, may be stretched to
any size by dragging with the mouse.System Information
One of the duties of the system administrator is to be aware of the settings and
activities on a system
/etc/redhat-releases:
This file contains the version number of the currently installed operating
system.
Uname:
This command prints information about the current system.
ifconfig:
This command, when enters with no arguments, list the active interfaces
Who:
Display information about the list of user logged on and their login time.
Last:
List of all logged in users
Free:
Display free and used memory.Scheduling Process
= at:
This command is used to schedule a process according to the
time parameters
= atq:
This command list the current at jobs pending
= atrm:
It is used to remove pending at jobs
= Cron:
This daemon wakes up every minute or so determines if an
entry in user’s cron table need to be executed. A cron job can
be scheduled as often as once a minute or as infrequently as
once a yearRPM Queries
Enables a user to build and query software package
RPM package filename of the format package-version-build-
architecture.rpm
RPM package installation:
rpm —ivh package name.rpm
RPM package Upgrade:
rpm —Uvh package name.rpm
RPM package “Freshening”:
rpm —Fvh packagename.rpm
RPM Package Removal
rpm —e packagename4 Programming Languages
= Languages and programming libraries supported by Linux
include:
Perl
Java
Gcc
Tel
Tk
Qt
Php
Expect.