You are on page 1of 150

Chapter-Two

INTRODUCTION TO LINUX

PREP BY: TEKALIGN T. 1


2.1 What is an Operating System (OS)?

 Software interface between the user and the


computer hardware
 Controls the execution of other programs
 Responsible for managing multiple computer
resources (CPU, memory, disk, display,
keyboard, etc.)
 Examples of OS: Windows, Unix/Linux, OS

Prep By: Tekalign T. 2


How does the Linux OS work?
 Linux has a kernel and one or
more shells
 The shell is the command line
interface through which the user
interacts with the OS.
 Most commonly used shell is
“bash”
 The kernel sits on top of the
hardware and is the core of the
OS;
 It receives tasks from the shell
and performs them.

PREP BY: TEKALIGN T. 3


2.2 History of Linux/Unix
History of UNIX Why LINUX/UNIX?
o UNIX is an Operating System
(OS).  LINUX is free.
o UNIX was developed about 40 • Can view and edit the source code of
years ago i.e., 1969 at AT&T Bell OS
Labs by Ken Thompson and
Dennis Ritche.  It is fully customizable.
o It is a Command Line  Most Important Feature is Stability
Interpreter.
• 30 years to get the bugs
o It was developed for the Mini-
Computers as a time sharing • Important in shared environments and
system. critical applications
o UNIX was the predecessor of  LINUX has better security
LINUX.
structure.
History of LINUX  High Portability
o LINUX was created by Linus • Easy to port new H/W Platform
Torvalds in 1991.
o LINUX is a open source. • Written in C which is highly portable
o LINUX is a variant of UNIX.

PREP BY: TEKALIGN T. 4


Some key events in the history of
Linux

PREP BY: TEKALIGN T. 5


Linux licensing and what 'Free
Software' means
The linux kernel and most linux applications are distributed under
Open Source licenses.
A number of open source licenses have been developed.
o GPL (GNU Public License) is the best known and is often
adopted by software developers who do not have the skill or
interest to develop their own licenses
o LGPL (Lesser General Public License)
o Many others ... see www.gnu.org/licenses/license-list.html
Freedom of software refers to liberty not price
o Freedom to run the program
o Freedom to study the program and adapt it for your needs
o Freedom to redistribute copies
o Freedom to improve the program and release the improvements
o See www.opensource.org for a more detailed definition

PREP BY: TEKALIGN T. 6


2.3 Definitions Linux
There are three definitions of Linux:-
Linux Kernel: The very low-level software that manages
your computer hardware and provides a library (POSIX)
interface for user-level software.
o The Linux kernel runs on many platforms (Intel x86 and IA-64, Alpha,
MIPS, HP PA-RISC, Power PC, IBM S/390, SPARC, Motorola 680x0, etc.).

GNU/Linux OS: The Linux kernel plus utility software to


provide a useful working environment.
Linux Distributions: The packaging of the Linux Kernel,
the GNU/Linux OS and lots of other software to make
Linux easy to install, configure, and use (at least for the
target audience).

PREP BY: TEKALIGN T. 7


Linux Distributions
 Strictly speaking, 'linux' refers only to the operating system
kernel.
o In practice, linux distributions include hundreds of additional items of
software from dozens of development teams
 In theory, all the pieces can be downloaded from the internet free of
charge and assembled into a working system.
o In practice this is hard work
 Most users purchase a pre-built distribution.
 Vendors such as RedHat and SuSE add value in several ways:
o Installation and configuration tools
o Supported ports of Linux to non-PC architectures (eg IBM
mainframes)
o Retail products include printed manuals and limited installation
support.
o Enterprise products provide full support agreements and pro-active
upgrade mechanisms

PREP BY: TEKALIGN T. 8


The components of a Linux
distribution

PREP BY: TEKALIGN T. 9


How does Linux differ from
windows?

 ~~Group
Discussion~~
Earn points…

PREP BY: TEKALIGN T. 10


Linux is Multi-User
Like later versions of windows, linux supports a user login.
o Authenticated by a password.

Linux supports multiple simultaneous logins.


o One on the main console, possibly running a graphical desktop.
o Several via character terminals connected to serial ports.
o Many via network logins using: telnet, rlogin, or ssh.

All users have full command line access.


Multiple graphical logins are also possible.
o Each user has an independent desktop.
o This capability is inherent in the client/server
architecture of the X window system.

Underlying operating system supports


pre-emptive multi-tasking.

PREP BY: TEKALIGN T. 11


Linux runs on a wide variety of
hardware
Embedded linux.
o Phones, set-top boxes, PDAs, PC104 and other single
board computers
o ARM, MIPS processors, etc.
o Specialist market, commercial support from companies
like Montavista
Mainstream (32-bit and 64-bit)
oIntel pentium, PowerPC, SPARC, Itanium, AMD64
 Big Iron
oIBM z/series mainframe

PREP BY: TEKALIGN T. 12


The X Window System is optional
 The X window system is not an integral part of the operating system.
o Linux can run with no windowing system or graphical
applications.
o Many servers are run this way.
◦ Configured and administered entirely using command-line
tools

 Saves on disk space, memory and CPU cycles

PREP BY: TEKALIGN T. 13


2.4 Layers of Linux/Unix
 LINUX/UNIX has three most important
parts.
 They are Kernel, Shell and File System

PREP BY: TEKALIGN T. 14


…(con’t)
Kernel File System
 Heart of the Operating (UNIX/Linux) system.
 It is the low level core of the System that is the  Linux treats everything as
interface between applications and H/W a file including hardware
 When a system boots its functions are:- devices.
• Managing the system resources (Manage  Arranged as a
Memory, I/O devices)
directory hierarchy.
• Allocating time for different users &
processes.  The top level directory is
• Deciding process priorities & performing known as “root (/)”.
them.
• Manages data/file access and storage.
• Enforces security.
• Performs all hardware access.
• inter process communication
 Init : First program run by kernel on
booting.

PREP BY: TEKALIGN T. 15


…(con’t)
Shell: Mediator between user and kernel.
 Unix shell interacts with us and the computer.
 Interprets commands typed by user, conveys them to the Kernel that
executes them.
 The shell operates in a command
 Some of its features are : processing loop:
• Interactive Processing. o Displays a 'prompt' and reads a command line
• Background Processing o Performs various substitutions and
• I/O Redirection. expansions on the command line
• Pipes. o Executes the resulting command and waits for
• Wild card Patterns. it to finish
• Shell Scripts. o Loops back and prompts for another
• Shell Variables command
• Programming language. o The core feature set of all these shells is very
• Presents each user a prompt, similar

PREP BY: TEKALIGN T. 16


…(con’t)
Types of Shell
 Bourne Shell (sh)  Korn Shell
 Primary unix command interpreter.
 Enhancement in C shell.
 Prompt being ($)
 Prompt being ($).
 Created by Steve Bourne.
 Created by David Korn.
 C Shell
 ksh command used to move
 Created by Bill Joy. to C shell.

 Prompt being (%) .


 csh command used to move to C shell.

PREP BY: TEKALIGN T. 17


Basic use of the shell
 Basic use of the shell

Simple commands

Command options

Command arguments

Command history

PREP BY: TEKALIGN T. 18


Logging in
After booting, a desktop system will usually present a graphical login dialog

o Enter your login name and password (both are case sensitive)

Systems (eg servers) which do not run a graphical desktop will present a
command line login

o Enter login name and password

o A 'shell' (command interpreter) is started

Please log in now:

o Log in as the user ……………………….

o Supply the password …………………..

PREP BY: TEKALIGN T. 19


Logging out
To logout from a command-line environment:
o Enter the “end of file” character (usually ^D)

o Or type the command exit

Please:
o Log out

o Log back in again

PREP BY: TEKALIGN T. 20


2.5 Linux System Architecture

PREP BY: TEKALIGN T. 21


…(con’t)
 Kernel
– The part of an OS where the real work is done

 System call interface


– Comprise a set of functions (often known as API) that can be used by the
applications and library routines to use the services provided by the kernel
 Application User’s Interface
– Interface between the kernel and user

– Allow user to make commands to the system


– Divided into text based and graphical based
 File Management
– Control the creation, removal of files and provide directory maintenance

– For a multiuser system, every user should have its own right to access files
and directories
 Device drivers
– Interfaces between the kernel and the BIOS
– Different device has different driver

PREP BY: TEKALIGN T. 22


…(con’t)
 Process Management
– For a multitask system, multiple programs can be executed
simultaneously in the system
– When a program starts to execute, it becomes a process
– The same program executing at two different times will become two
different processes
– Kernel manages processes in terms of creating, suspending, and
terminating them.
– A process is protected from other processes and can communicate with
the others
 Memory management
– Memory in a computer is divided into main memory (RAM) and secondary storage
(usually refer to hard disk)
– Memory is small in capacity but fast in speed, and hard disk is vice versa
– Data that are not currently used should be saved to hard disk first, while data that
are urgently needed should be retrieved and stored in RAM
– The mechanism is referred as memory management

PREP BY: TEKALIGN T. 23


Managing files
 Managing files

The current directory


Creating and deleting directories
Listing directory contents
Copying files
Renaming files
Deleting files
Updating files

PREP BY: TEKALIGN T. 24


Setting and querying the current
directory
Every process (including the shell) has a current directory Where it will
look for 1 relative path names.
Frequently used commands available in most shells:
o ls : to show the names of the file in the current directory
o cd : change the current directory.
e.g. cd / change to the root directory
cd .. change to the parent of that directory
o rm : remove a file
o man : ask for the manual (or help) of a command
e.g. man cd ask for the manual of the command cd
o pwd : show the name of the current directory
o cat : to show the content of a text file
e.g. cat abc.txt show the content of abc.txt
o whoami : to show the username of the current user

PREP BY: TEKALIGN T. 25


Example

PREP BY: TEKALIGN T. 26


Listing Directory contents with the ls
command

PREP BY: TEKALIGN T. 27


PREP BY: TEKALIGN T. 28


Hidden files
 Files whose names begin with a '.' are “hidden”
o They do not show up on a normal directory listing

o Most of them are configuration and startup files, for example:

◦.bash_history: Where the bash shell stores its command history

◦.xinitrc: Startup file for the X window system

◦.bashrc: Startup file for the bash shell

◦.profile: Startup file for all shells

Use ls -a to show hidden files

PREP BY: TEKALIGN T. 29


Copying files with the cp
command
 The cp command copies files
$ cp file1 file2
o This form makes a copy of file1 under the name file2
$ cp file1 file2 ... dir
o This form makes copies of file1 file2 ... in (existing) directory dir
 Beware: the destination files will be replaced if they already exist
o Options include:

PREP BY: TEKALIGN T. 30


Renaming files with the mv
command
The mv command renames or moves files
$ mv file1 file2
This form renames file1 as file2.
$ mv file1 file2 ... dir
This form moves file1 file2 ... into (existing) directory dir
Beware: the destination files will be replaced if they already exist
Options include:

PREP BY: TEKALIGN T. 31


Deleting files with the rm
command
The rm command deletes files
$ rm file1 file2 ...
Beware: there is no 'undelete' command!
Options include:

PREP BY: TEKALIGN T. 32


Updating files with the touch
command
 The command touch updates the access and modification
timestamps on a file to the current time
• Makes it appear that the file has just been modified
• If the file does not exist it is created with zero length
$ touch file1 file 2 ...
 Options for touch include:

PREP BY: TEKALIGN T. 33


Simple commands
Try these simple commands:
$ hostname Do now!
snowhite
$ date Reports the name
Fri Apr 16 11:48:33 BST 2013 of this machine
$ id
uid=500(chris) gid=100(users)
groups=100(users),14(uucp)
$ cal
April 2004
Su Mo Tu We Th Fr Sa For simplicity we show the prompt
1 2 3 as a '$'.
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

PREP BY: TEKALIGN T. 34


Command options
 Command options modify the behaviour of a command
o Usually, an option is a single letter prefixed by '-‘ (short options)
$ cal -y
... calendar for the entire year ...
$ date -I Options are case sensitive

2004-04-16 The date in ISO format


 Some commands also have 'long' options.
• Begin with '--'
• Supplement or replace the traditional single character options
$ date --iso-8601
2004-04-16

PREP BY: TEKALIGN T. 35


Command arguments
 Most commands accept arguments
o The command name, options, and arguments are separated by whitespace
(spaces and tabs)
o Arguments are often the names of files or directories on which to
operate
$ cal 1955
ls lists the contents of the
... calendar for the year 1955 ...
$ ls /home specified directory /home
chris dilbert tux
 Options and arguments are often used together:
The -l option requests
$ ls -l /home a 'long' listing
total 6
drwxr-xr-x 66 chris users 3328 2004-04-16 11:48
chris
drwxr-xr-x 17 dilbert users 1112 2004-02-09 11:52
dilbert
drwxr-xr-x 18 tux users 1240 2004-03-30 20:29
tux

PREP BY: TEKALIGN T. 36


Command history
 bash remembers the most recent commands you've entered
o stored in the file .bash_history in your home directory
o survives across logout / login, shared by all instances of bash
o size of history file is configurable, set to 500 commands in SuSE Linux
 The history command shows your command history
history shows your entire command history
history 10 shows the last ten commands
history -c clears your command history
 Previous commands can be selected and re-executed
!85 re-execute command 85
!string re-execute most recent command that began with string
!! re-execute last command

PREP BY: TEKALIGN T. 37


…(con’t)
 You can also edit your command history on screen.
o The following keys are used:

PREP BY: TEKALIGN T. 38


…(con’t) Exercise
 To provide you with a command history, execute the following commands:
$ pwd
$ hostname
$ cal -y
$ date Do now!
$ id
$ ls /etc/hosts.allow
$ cat /etc/fstab

1. Recall your command history with the history command.


2. Recall the date command by command number.
3. Recall the most recent command beginning with 'ho‘.
4. Using the arrow keys, recall the 'ls' command, changing the file name
from hosts.allow to hosts.deny.

PREP BY: TEKALIGN T. 39


2.6 The file system hierarchy or structure
 The file system hierarchy

PREP BY: TEKALIGN T. 40


The File System
 In general File system refers to a collection of files in UNIX.

 A file system is a way of storing data on a medium: the way it is


organized and managed.

 The file system in Linux/Unix is organized in a hierarchy (tree)

oThe “root directory” (/) is at the top of the tree


 Pieces of the file system may exist on multiple disk partitions or on
remote file servers on the network

oThe pieces are 'mounted' onto directories to make the file


system appear as a single tree

PREP BY: TEKALIGN T. 41


…(con’t)
A directory in Linux is similar to a “Folder” in
Windows OS
Files are organized into directories and sub-
directories
In Linux, paths begin at the root directory which
is the top-level of the file system and is
represented as a forward slash ( / )
Forward slash is used to separate directory and
file names

PREP BY: TEKALIGN T. 42


…(con’t)

PREP BY: TEKALIGN T. 43


File types
 Several types of object exist in the file system

 Normal files
o A set of contiguous data identified by a name.

o Includes text files, graphics files, executable programs( c++ file etc;

o The file system does not distinguish the type of data

 Directories
o Directories contain named 'links' to other files

o They cannot be opened, read and written like ordinary files

PREP BY: TEKALIGN T. 44


…con’t

PREP BY: TEKALIGN T. 45


…con’t
 Device Files
o Devices (disks, tape drives, mice, etc) are identified by device file entries
which are usually in the /dev directory
o If access permissions allow, some device files may be opened, read and
written like ordinary files (for example an archive may be written directly
to a tape device)

 Symbolic Links
o References to files located at other points in the file system
o Allow a single file to be referenced using multiple names
o Symbolic links can be opened like regular files, but the operation is
automatically redirected to the file that the link points to.

 Sockets and FIFOs (named pipes)


o Named communication end points used for inter process communication.

PREP BY: TEKALIGN T. 46


…con’t

PREP BY: TEKALIGN T. 47


…con’t

PREP BY: TEKALIGN T. 48


File names
 File names can be up to 255 characters long

o Case sensitive

 All characters except '/' are legal in filenames

o '/' is used as a separator in path names

 Some characters have special meaning to the shell. They are awkward
to work with in file names and are best avoided:

o +, %, $, #, !, \, -, ~, =, space, others ...

o Recommend use only upper and lower case letters, digits, and '_'

 Maximum length of a path name is 4096 characters

PREP BY: TEKALIGN T. 49


Root directory and Root Partition
 The root directory is the top level directory of the tree
o Do not confuse this with the home directory of the super user,
which is usually /root.

o Similar to \ in DOS

 The root partition is the partition containing the root directory.


o At boot time, the root partition is initially the only one mounted

o Files needed at boot time must be in directories on the root


partition

o /bin, /dev, /etc, /lib and /sbin

PREP BY: TEKALIGN T. 50


Binary directory: /bin
 /bin contains important executable (binary) programs
o Needed early in boot sequence
o Needed for emergency maintenance if other partitions unavailable
o Includes shells, file system maintenance commands, other tools
o Contents include:

PREP BY: TEKALIGN T. 51


Boot directory: /boot
 /boot contains the files needed to get the linux kernel up and running
o Second-stage files for the boot loader (GRUB or LILO)
o Backup of Master Boot Record
o The image of the linux kernel

 Sometimes /boot is on a separate partition


o Early stages of booting on a PC rely on the PC's BIOS firmware to
access the hard drive.
o On early PCs the BIOS could not access cylinder numbers beyond
1023 so it was essential that the kernel image lay below this
boundary
o Putting /boot on a separate (small) partition guarantees this.

PREP BY: TEKALIGN T. 52


Device files: /dev
Device files give file
names to hardware
devices.
Holds the Device files
(device drivers)
necessary to operate
peripherals such as
printers and terminals.
These are special files
that help the user
interface with the
various devices on the
system.

PREP BY: TEKALIGN T. 53


Configuration files: /etc
 /etc contains system configuration
files
o Configuration files specific to the
machine. i.e, contains additional
commands that are related to system
maintenance and administration. (for
e.g. files such as lists of user names and
passwords.)
o It also contains several system files
which store the relevant
information about the users of the
system, the terminals and devices
connected to the system.
o mostly plain text; editable using
any text editor.

PREP BY: TEKALIGN T. 54


User directories: /home
 /home contains the home directories of individual users
o After login, a user's current directory is his home directory

 /home is often on a separate partition


o or may be mounted from a file server – this arrangement means that
users are not tied to specific machines

 A user's personal configuration files are stored in his home directory

o “Hidden” files (name starts with '.')


o Examples: .bashrc, .profile, .bash_history, .xinitrc
o The shell recognizes '~' as a shorthand for your home directory
o Example: ~/.bashrc

PREP BY: TEKALIGN T. 55


Libraries: /lib
A library is a collection of compiled binary files
o Contains code for functions used by many programs
o A program that needs access to library functions links to the required
libraries at run time (dynamic linking)
o UNIX refers to dynamically linked libraries as shared objects (so.files)

 /lib contains the essential system libraries needed to run the


commands in the root file system i.e. /bin and /sbin
o /lib/libc.so.6 is the main C runtime library
o Most other application libraries are in /usr/lib

PREP BY: TEKALIGN T. 56


Directory of applications /opt
 The /opt directory is used to store the 'static' files of additional
applications such as Netscape, Gnome, KDE, or Open Office
$ ls /opt
cxoffice gnome kde3 mozilla OpenOffice.org

 Note that the open source community does not always follow this
guideline. When applications are installed by compiling from source
code, the default installation directory is usually /usr/local

o This can be changed using command line options when the application is
installed

PREP BY: TEKALIGN T. 57


Process files /proc
 The files in /proc are a creation of the kernel's imagination

o Make internal kernel information available via normal file read


commands

o The /proc file system contains a illusionary file system. It does not
exist on a disk. Instead, the kernel creates it in memory.

o It is used to provide information about the system (originally about


processes, hence the name).

o There is a subdirectory for each process, named after the process ID

o Other 'files' in /proc provide information about the system as a whole.

PREP BY: TEKALIGN T. 58


…(con’t)

PREP BY: TEKALIGN T. 59


Directory of the administrator
/root
 The super-user's home directory is /root
o On the root partition

o Allows root to login even if no additional partitions can be


mounted – the home directories for ordinary accounts (under
/home) may be on a separate partition

PREP BY: TEKALIGN T. 60


System administration commands:
/sbin
 /sbin contains binaries essential for booting, restoring,
recovering, configuring or repairing the system
o Usually only root can run these programs to make changes to the system

o /sbin lies in the root partition

PREP BY: TEKALIGN T. 61


Temporary area
/tmp contains temporary files.
o Anyone can create files in /tmp

o Programs should not rely on files surviving in /tmp between one


program invocation and the next.

o Some administrators set up the system to empty /tmp at boot


time.

o Important to avoid name clashes in /tmp – some applications


include their process ID within the file name.

PREP BY: TEKALIGN T. 62


The /usr hierarchy
 Defines a second level of directories under /usr
o Sharable (across machines); “static” files that do not normally change

o Subdirectories include:

PREP BY: TEKALIGN T. 63


Changeable files: /var
 /var contains data files that change during normal system operation
o Spool directories and files
o Administrative and logging data
o Transient and temporary files
o Key subdirectories include:

PREP BY: TEKALIGN T. 64


Example
 davis:x:134:105:James A Davis:/home/davis:/bin/bash
– davis : login name
– x : means that it is a dummy password. The encrypted
password is stored in /etc/shadow. This field can also be used
to store the actual encrypted password. In any case, the
original (unencrypted) password cannot be seen by anyone,
including the administrator
– 134 : a user id given to that user. Range from 0 to 65535. 0 is
assigned to super-user. 1 to 99 are reserved
– 105 : a group id given to that user to indicate which group he
belongs to. Range from 0 to 65535. 0 to 99 reserved
– James A Davis : user info, usually user’s full name
– /home/davis : home directory of the user
– /bin/bash : the location of the shell the user is using

PREP BY: TEKALIGN T. 65


Mount points
 The file system is often split across several disk partitions
o Each partition has a self-contained file system structure
o Directories (“mount points”) are created on the root file system
o The mount command attaches a partition's file system to a mount point
o The umount command detaches a file system

PREP BY: TEKALIGN T. 66


Pre-defined mount points
 The (empty) directory /mnt is provided as a general-purpose mount
point for temporary mounts
 Directories under /media are provided for mounting removable
media
o floppy Floppy disks
o cdrom Droms
o dvd DVDs
o Cdrecorder CD Recorders
o sda1 SCSI disk or devices emulated as SCSI
e.g. USB memory sticks

 By default, only root can mount or unmounts


 But the system is usually configured to allow non-root users to
mount removable media

PREP BY: TEKALIGN T. 67


File system hierarchy quiz TRY YOUR SELF

 Where would you expect to find:


o The configuration file for the samba file server
o Dilbert's home directory
o The super user's home directory
o The “spool files” that hold incoming mail.
o The bootable linux kernel image.
o A file system mounted from a floppy disk.
o The device entries for the partitions on your hard drive
 True or false?
o The mount command must be in the root partition

PREP BY: TEKALIGN T. 68


File system types
 File system types

Native Linux file system formats

File system formats of other systems

Network file system formats

The ext2 file system

PREP BY: TEKALIGN T. 69


Native Linux file system formats
 Linux supports many file system formats.

o ext2

o Probably the most common 'native' linux file system format.

o ext3

o Extension of ext2.
o Much faster to check file system consistency after a crash
 Can choose file system types at installation time

PREP BY: TEKALIGN T. 70


File system formats of other systems
 Linux also supports the native file systems of other operating
systems.
o Useful on dual-boot systems
 FAT, VFAT
o Used on floppies, and Windows 95/98
 NTFS
o Used on Windows NT, 2000, XP
 HPFS
o Native file system of OS/2
 CDROM
o ISO9660

PREP BY: TEKALIGN T. 71


Absolute pathnames

PREP BY: TEKALIGN T. 72


…(con’t)
 The linux file system is organised in a tree structure
 The top level directory of the tree is called the root directory and
is named '/'
 A file or directory can be referenced using an absolute
pathname
o Starts with a '/'
o Traces a path from the root of the tree to the file
o Uses '/' (forward slash) to separate components of the pathname
 Examples:
/etc/at.deny
/home/dilbert/travel
/home/tux/reports/quality

PREP BY: TEKALIGN T. 73


Relative pathnames
 Pathnames not beginning with '/' are relative to the current
directory
 Examples (assuming /home/tux is the current directory):
reports
code/main.c
 Every directory has a special entry named '..' which references the
parent directory
o The directory immediately above it in the tree
 Use relative pathnames beginning with '..' to move outside the
current directory
 Examples (assuming /home/tux/code is the current directory):
../reports/July_Conf
../../dilbert/travel/paris

PREP BY: TEKALIGN T. 74


File name completion
When entering a command, bash will perform filename completion
o Press the TAB key
o bash will complete as much of the name as is unambiguous, based on
the name completed so far and the names of the existing files
o Less typing, less chance for typing mistakes
o If there are several possible matches, [TAB] [TAB] will show them all
Example ([T] denotes the TAB key)
$ ls -l /h[T]/t[T]/re[T]/Ju[T] ... completes to:

$ ls -l /home/tux/reports/July_Conf

Using file name completion to minimize typing, do a long directory


listing (ls -l) on these files:
/usr/X11R6/bin/showfont
/usr/share/xscreensaver/screensaver-diagnostic.xpm Do now!
/boot/vmlinuz.config

PREP BY: TEKALIGN T. 75


PREP BY: TEKALIGN T. 76
2.7 Linux File Access Privilege
The user root
 Linux has a privileged user account called the super-user
 The account name is usually root
 The numeric user ID is zero
 Root can access or modify any file or directory and run any command
 Only log in as root if you are doing something that requires it
 You can start a new shell as root using the su command
 To become superuser on Ubuntu Linux
 Open a terminal Window. Press Ctrl+Alt+T to open the terminal on Ubuntu
To become root user type: sudo –i OR sudo -s
 When promoted provide your password
 After successful login, the $ prompt would change to # to indicate that you logged in
as root user on Ubuntu

PREP BY: TEKALIGN T. 77


User identity and the super
user
 Log in as………, with password …………. Do now!
o What is your prompt string? _________________
 Run the id command
o What is your numeric user ID? _____________
o What is your primary group name? ___________
o What are the names of your secondary groups? ___________
 Run the command 'su -' to start a shell as the super user
o Supply the password for the root in your system
o What is your prompt string? _________________________
o What is your numeric user ID now? ____________________
o What is your primary group ID? ________________
 Type exit (or enter ^D) to exit from your super user shell
o Confirm (from your prompt) that you are no longer logged in as root

PREP BY: TEKALIGN T. 78


Standard file permissions
 Every file and directory has a set of attributes:
o An owner (by default, the person who created it)
o A group (by default, the primary group of the person who created
it)
 Three sets of access permissions, relating to:
o The owner of the file
o Users who are members of the file's group
o Everyone else (“others”)
 These attributes are shown in a long directory listing:

PREP BY: TEKALIGN T. 79


…con’t
 Linux is a multiuser system, the files of all users are stored in a single
file structure
 Mechanism is required to restrict one user to access the files of another
user, if he is not supposed to
 User can impose access permission to each file to restrict its access
 The term “access permission” refers to
– read permission
– write permission
– execute permission

PREP BY: TEKALIGN T. 80


…con’t

PREP BY: TEKALIGN T. 81


…con’t

The group of a user is assigned by the administrator when a user is


added to the system

PREP BY: TEKALIGN T. 82


…con’t
 Access permission can also be assigned to a directory
 Directory is also a file that contains the attributes of the files
inside it
 If read permission is not given to a directory
o cannot show the structure of this directory
o e.g. cannot use ls
 If write permission is not given to a directory
o cannot modify anything of the directory structure
o e.g. cannot copy a file into this directory since it will modify
the directory structure by adding one more file
 If execute permission is not given to a directory
o nearly nothing can be done with this directory, even cd

PREP BY: TEKALIGN T. 83


…(con’t)
 The permissions are shown as a group of nine characters,
 for example:
rwxr-xr-x
 The access permission of a file or directory can be
changed by using the command
chmod xyz filename/directory name
 xyz refers 3 digit in octal form
 E.g. 660 : 110 110 000
 rw- rw- ---
545 : 101 100 101
 r-x r-- r-x
PREP BY: TEKALIGN T. 84
…con’t

PREP BY: TEKALIGN T. 85


Changing access permissions with
chmod
The command chmod is used to change file permissions
How to build yourself a chmod command in five easy lessons

PREP BY: TEKALIGN T. 86


…con’t
 Only the owner of a file (or the superuser) can change the file’s
permissions
$ chmod u+x hello.txt
$ chmod go-w display.object
$ chmod a-wx opensource openwindows
$ chmod u=rw open*
 To set different access permissions for different users, either use
two chmod commands or separate changes with a comma:
$ chmod u=rwx index
$ chmod go=r index
Or:
$ chmod u=rwx,go=r index
 Question: What do you think 'chmod u=rwx go=r index' does?

PREP BY: TEKALIGN T. 87


Representing file permissions in
octal
 Since each of the file permissions (rwxrwxrwx) is either on or off, a file’s
permissions can be represented by 3 groups of 3 binary digits
o Then each set of 3 bits can be written as an octal digit (0-7)

rwx rw- r-- 0-no permission, 4 -read , 2-write, 1-execute.


3- write & execute
111 110 100 5-read & execute
7 6 4 6-read & write
7-read, write & execute.
 This notation can be used by chmod; e.g.
$ chmod 644 hello.txt
$ chmod 400 hello.txt
 Some early versions of chmod, and a few other commands which deal
with access permissions, only understand the octal notation

PREP BY: TEKALIGN T. 88


Changing ownership with chown
 The chown command can change the ownership and group of a file
chown owner1 file1 file2 ...
 Example:
$ chown tom foo bar
To change the group ownership
$ chgrp wheel bar
 Only root can change a file's owner
o Ordinary users can change a file's group only if they are members of both
the original and the new group

PREP BY: TEKALIGN T. 89


PREP BY: TEKALIGN T. 90
Exercise continued
4.As the user ………(your username). try to change the ownership of the file
sample to be owned by the user ………(any other username).

o What happens?
5.Use the su command to switch to a super user shell

o Try again to change sample to be owned by dilbert


(It should work this time)
o Change the group ownership of sample to the group …..(specify any
other group)
6.Exit from the super user shell

7.Do a long listing of sample and verify the ownership and group.

PREP BY: TEKALIGN T. 91


Changing passwords
 Users are allowed to change their own password
o A simple password strength check is enforced
$ passwd
Changing password for tux.
Old Password: penguin In reality the passwords
New password: secret are not echoed to the screen
Bad password: too simple
New password: SuSE2004
Re-enter new password: SuSE2004
Password changed
 The super user can change anyone's password
# passwd dilbert
Changing password for dilbert.
...

PREP BY: TEKALIGN T. 92


User account management
 User account management

Creating user accounts from the command line


Modifying user account defaults
Modifying and deleting existing accounts
Managing groups from the command line
Exercise: User account management
Command-line vs graphical tools

PREP BY: TEKALIGN T. 93


Creating user accounts from the
command line
 Root can create user accounts with the command useradd
# useradd kurt
o The UID will be one bigger than the largest currently in use
o Other defaults (location for home directory, shell, etc) are taken from
the file /etc/default/useradd
 Root should set an initial password for the account (and tell the user!)
 Command options can be used to specify non-default settings, e.g.

PREP BY: TEKALIGN T. 94


Modifying user account defaults
 Root can modify the defaults for new user accounts, for example:
# useradd tom -s /usr/bin/csh
This example changes the
default shell. Also use:
-d homedir
-g GID
-G group1,group2
 Subsequently, new users will receive a csh by default
 we can create user’s with custom userid with ‘-u‘ option. For example, the following
command will create a user ‘admin2‘ with custom userid ‘999‘.
#useradd -u 999 admin2
 Now, let’s verify that the user created with a defined userid (999) using following
command.
#cat /etc/passwd | grep admin2
Output
admin2:x:999:999::/home/admin2:/bin/bash

PREP BY: TEKALIGN T. 95


Modifying and deleting existing
accounts
 Root can modify existing accounts using usermod, for example:
# grep dilbert /etc/passwd
dilbert:x:501:100:Dilbert:/home/dilbert:/bin/bash
# usermod -c "My Hero" -s /usr/bin/csh dilbert
# grep dilbert /etc/passwd
dilbert:x:501:100:My
Hero:/home/dilbert:/usr/bin/csh
o The options for usermod are similar to those for useradd
 Root can delete existing accounts using userdel, for example:
# userdel -r kurt

Forces removal of
kurt's home directory

PREP BY: TEKALIGN T. 96


Managing groups from the
command line
 Root can create groups with groupadd
# groupadd -g 1445 hackers

Specifies the GID. By default the


next available ID is allocated

 Root can delete groups with groupdel


# groupdel hackers
• You are not allowed to delete a group which is someone's primary
group

PREP BY: TEKALIGN T. 97


Exercise: User account management
1. Create a new group called hacker with group ID 1200

2. Create two new users with user names catbert and dogbert and UIDs 610
and 611 respectively. Their home directories should be created as
/new1/catbert and /new1/dogbert and should be populated with initial
configuration files from /etc/skel. Their primary group should be
hacker and they should both have secondary membership of the groups
audio and video

3. Set passwords for these two accounts. Make sure you remember them!

4. Examine the /etc/group and /etc/passwd files and verify that the entries
for the hacker group and the catbert and dogbert accounts are as you
expect.

PREP BY: TEKALIGN T. 98


Exercise(con’t)
5. Set password aging on catbert's account so that:
o The minimum time between password changes is 1 week
o The maximum time between password changes is 1 month
o He receives 2 days warning of password expiry
o The account is usable for 3 days after the password expires
o The account expires on 31 December this year
oHint – look up the man page for chage
6. Look up catbert's entry in /etc/shadow and examine the password
aging parameters. Are they what you expect?
oHint – man 5 shadow will help you figure out which field is which
7. List the /new1 directory. Verify that catbert and dogbert's home
directories exist.
oWho are they owned by? What group do they belong to?

PREP BY: TEKALIGN T. 99


Exercise(con’t)
8. Verify that you can log in as catbert
o Run the command id to verify catbert's UID and group
memberships.
Are they what you expect?
o Run the command pwd and verify the path name of the home
directory
o Create a file in the home directory and verify its ownership and
group
o List the hidden files in the directory. Where have these come
from?
9. Still as catbert, try to change your password. What happens?
End of Exercise

PREP BY: TEKALIGN T. 100


Command-Line vs Graphical
Tools
Advantages of graphical tools
o No need to remember command line syntax or file formats
o Less likely to create an invalid configuration
o Closer match to expectations of administrators migrating from
Windows
The use of graphical tools does not mean that you don't need to
understand the underlying model
Advantages of command line tools
o Generally faster, once you know them
o Do not require a graphical desktop
o System admin can be automated, using scripts
o May offer greater flexibility than the graphical tools

PREP BY: TEKALIGN T. 101


Searching for patterns with grep
 The program grep searches one or more text files for lines that match a
specified pattern. At its simplest, it is used like this
$ grep 'string' file1 file2 ...
o Lines in the file(s) that contain a match for the string are displayed
o Note: putting the string inside single quotes is not always necessary but is good
practice.
Examples:
$ grep 'tux' /etc/passwd
tux:x:504:100:Tux Penguin:/home/tux:/bin/bash
$ grep 'Clothes' shopping

PREP BY: TEKALIGN T. 102


Options for grep
 Command line arguments for grep include:

PREP BY: TEKALIGN T. 103


Counting characters, words and
lines with wc
 The command wc counts lines, words and characters in its input
files.

 Command line options include:

PREP BY: TEKALIGN T. 104


Sorting a file with sort
 The sort command sorts its input Example of sort
line by line
o By default, does alphanumeric
sort on entire line

 Command line options include:

PREP BY: TEKALIGN T. 105


Reading Assignment
Filter programs commands
Displaying the start of a file with head
Displaying the end of a file with tail
About pipeline with examples

PREP BY: TEKALIGN T. 106


2.8 File storage in Linux
Data storage on hard disk
o Data in a hard disk are stored on a magnetic flat plate
o Disk’s surface needs to be partitioned and labeled so
that computer can go directly to a specific point on it
o Achieve by low level formatting the disk
• Create magnetic concentric circles called tracks
• Each track is split into smaller parts called sectors
and numbered
Each sector: hold 512 bytes data
o E.g. 80 tracks (from outer to inner 0 .. 79), 18 sectors
disk can store 80x18x512 bytes data.

PREP BY: TEKALIGN T. 107


…con’t
Formatted Disk
Sector Density of data is
higher for inner tracks
Track
than outer tracks

PREP BY: TEKALIGN T. 108


…con’t
 Must read or write whole sector at a time
 OS allocates groups of sectors called cluster to files
 Files smaller than the cluster will still be allocated the
whole cluster, but the rest left unused
 In Linux, every file is associated with an inode that
records its location in the disk
 The inode of all files are put together in a data structure
called inode table
 In the directory, every file is associated with a inode
number that points to an entry of the inode table

PREP BY: TEKALIGN T. 109


…con’t
Contents of the directory /home/dlun

PREP BY: TEKALIGN T. 110


2.9 Linux Process management
 Linux is a multitasking system

 Multiple programs can be executed at the same time

 Ultimately, a program needs to be executed by a CPU

 If there is only one CPU, how multiple programs can be


executed at the same time?

 By time sharing

 That is, all programs are claimed to be executing. In fact,


most of them are waiting for the CPU.

PREP BY: TEKALIGN T. 111


…con’t
 A program that is claimed to be executing is called a
process
 For a multitasking system, a process has at least the
following three states:

PREP BY: TEKALIGN T. 112


…con’t
Ready state
o All processes that are ready to execute but without the CPU
are at the ready state
o If there is only 1 CPU in the system, all processes except one
are at the ready state
Running state
o The process that actually possesses the CPU is at the
running state
o If there is only 1 CPU in the system, at most there is only one
process is at the running state
Sleeping state
o The process that is waiting for other resources, e.g. I/O, is at
the sleeping state

PREP BY: TEKALIGN T. 113


…con’t
 Processes will alternatively get into the CPU one after the
other (called the round robin scheme)
 A process will be “in” a CPU for a very short time (quantum)
o For Linux, each quantum is about 100msec
 At the time that a process is selected to be “in” the CPU
o It goes from ready state to running state
 After that, it will be swapped out
o It goes from running state back to ready state
 Or it may due to the waiting of an I/O device, e.g. mouse
o It goes from running state to sleeping state
 When obtaining the required resource
o It goes from sleeping state to ready state
PREP BY: TEKALIGN T. 114
…con’t
ready C A B C A B
B A B A B C A B C A C A B A

running A B A B A B C A B C A C A B
Time
C Executes
B Sleeps
B Awakes
C Terminates

B B
sleep

PREP BY: TEKALIGN T. 115


…con’t
 The mechanism to determine which process should “get
into” the CPU is called Process scheduling
 For example,
Program A Actual sequence of operations
a -> 10
Set variable a to 10 b -> 0
Set variable b to 0 c -> a+b
b -> c
Repeat 5 times the following c -> a+b
{ b -> c
c -> a+b
Set variable c to a+b
b -> c
Set variable b to c c -> a+b
} b -> c
c -> a+b
Print out the value of b b -> c
Print out b

PREP BY: TEKALIGN T. 116


…con’t
Program B Actual sequence of operations
d -> 0
Set variable d to 0 User -> e
f -> d+e
Repeat 5 times the following d -> f
User -> e
{ f -> d+e
Ask user to enter variable e d -> f
User -> e
Set variable f = d+e f -> d+e

Set variable d = f d -> f


User -> e
} f -> d+e
d -> f
Print out the value of d User -> e
f -> d+e
d -> f
Print out d

PREP BY: TEKALIGN T. 117


…con’t
 Program A and B will be at the running state alternatively, depends
on the quantum size and the availability of the required resource

PREP BY: TEKALIGN T. 118


…con’t

PREP BY: TEKALIGN T. 119


…con’t

PREP BY: TEKALIGN T. 120


…con’t
For the example above, both bash processes,
which are the shell of both terminals, are waiting
for the input of user.
o They must be in the sleeping state
The vi process, which is an editor, is also waiting
for the input of user.
o Hence it is also in sleeping state
When ps reporting the processes in the system,
it is the only process that is running.
o Hence it is in running state

PREP BY: TEKALIGN T. 121


…con’t
 A process can be forced to terminate by using the
command kill -9 PID

PREP BY: TEKALIGN T. 122


2.10 Starting the vi Editor
 The editor vi is the 'standard' editor on UNIX and Linux systems
 You can use vi editor to edit an existing file or to create a new file from scratch.
 You can also use this editor to just read a text file.

 Advantages:

o It is available on every UNIX and Linux system

o It works on character terminals, without a graphical user interface

o It is fast and powerful once you know it well

 Disadvantages:

o It is a 'moded' editor which makes it difficult to learn initially


o There are a lot of commands to remember
 Professional linux users and administrators benefit in the long term by learning vi.

PREP BY: TEKALIGN T. 123


Working modes in vi

PREP BY: TEKALIGN T. 124


Command mode in vi

PREP BY: TEKALIGN T. 125


“Bottom line” mode in vi

PREP BY: TEKALIGN T. 126


…con’t
 There are following way you can start using vi editor −

Command Description
vi filename Creates a new file if it already does not exist,
otherwise opens existing file.
vi -R filename Opens an existing file in read only mode.
view filename Opens an existing file in read only mode.

 Following is the example to create a new file testfile if it already does not exist
in the current working directory:
$vi testfile
 As a result you would see a screen something like as follows −
|
~
~

"testfile" [New File]

PREP BY: TEKALIGN T. 127


…con’t
 You will notice a tilde (~) on each line following the
cursor.
 A tilde represents an unused line.
 If a line does not begin with a tilde and appears to be
blank, there is a space, tab, newline, or some other no
viewable character present.
 So now you have opened one file to start with.
 Before proceeding further let us understanding few
minor but important concepts explained below

PREP BY: TEKALIGN T. 128


Operation Modes
 While working with vi editor you would come across following
two modes:
o Command mode − This mode enables you to perform
administrative tasks such as saving files, executing commands,
moving the cursor, cutting (yanking) and pasting lines or words, and
finding and replacing. In this mode, whatever you type is interpreted
as a command.
o Insert mode − This mode enables you to insert text into the file.
Everything that's typed in this mode is interpreted as input and finally
it is put in the file .
o The vi always starts in command mode. To enter text, you must be in
insert mode. To come in insert mode you simply type i. To get out of
insert mode, press the Esc key, which will put you back into
command mode.
o Hint − If you are not sure which mode you are in, press the Esc key
twice, and then you'll be in command mode. You open a file using vi
editor and start type some characters and then come in command
mode to understand the difference.

PREP BY: TEKALIGN T. 129


Getting Out of vi
 The command to quit out of vi is :q.
 Once in command mode, type colon, and 'q', followed by return.
 If your file has been modified in any way, the editor will warn you of this, and
not let you quit.
 To ignore this message, the command to quit out of vi without saving is :q!.
 This lets you exit vi without saving any of the changes.
 The command to save the contents of the editor is :w.
 You can combine the above command with the quit command, or :wq and
return.
 The easiest way to save your changes and exit out of vi is the ZZ command.
 When you are in command mode, type ZZ and it will do the equivalent of :wq.
 You can specify a different file name to save to by specifying the name after
the :w.
 For example, if you wanted to save the file you were working as another
filename called filename2, you would type :w filename2 and return.

PREP BY: TEKALIGN T. 130


Moving within a File
 To move around within a file without affecting your text, you must be in
command mode (press Esc twice).
 Here are some of the commands you can use to move around one
character at a time −

Command Description

k Moves the cursor up one line.

j Moves the cursor down one line.

h Moves the cursor to the left one character


position.
l Moves the cursor to the right one character
position.

PREP BY: TEKALIGN T. 131


…con’t
 There are following two important points to be noted:
o The vi is case-sensitive, so you need to pay special attention to
capitalization when using commands.
o Most commands in vi can be prefaced by the number of times you
want the action to occur. For example, 2j moves cursor two lines
down the cursor location.

 There are many other ways to move within a file in vi.


Remember that you must be in command mode (press
Esc twice).
Read some more commands you can use to move
around the file from handout:

PREP BY: TEKALIGN T. 132


Control Commands
 There are following useful command which you can use along with Control
Key:
Command Description
CTRL+d Move forward 1/2 screen
CTRL+f Move forward one full screen
CTRL+u Move backward 1/2 screen
CTRL+b Move backward one full screen
CTRL+e Moves screen up one line
CTRL+y Moves screen down one line
CTRL+u Moves screen up 1/2 page
CTRL+d Moves screen down 1/2 page
CTRL+b Moves screen up one page
CTRL+f Moves screen down one page
CTRL+I Redraws screen

PREP BY: TEKALIGN T. 133


Editing Files
 To edit the file, you need to be in the insert mode.
 There are many ways to enter insert mode from the command
mode:
Command Description

i Inserts text before current cursor location.

I Inserts text at beginning of current line.

a Inserts text after current cursor location.

A Inserts text at end of current line.

o Creates a new line for text entry below cursor


location.
O Creates a new line for text entry above cursor
location.

PREP BY: TEKALIGN T. 134


Deleting Characters
 Here is the list of important commands which can be used to delete
characters and lines in an opened file:
Command Description
x Deletes the character under the cursor location.
X Deletes the character before the cursor location.
dw Deletes from the current cursor location to the next word.
d^ Deletes from current cursor position to the beginning of the
line.
d$ Deletes from current cursor position to the end of the line.
D Deletes from the cursor position to the end of the current line.
dd Deletes the line the cursor is on.
 As mentioned above, most commands in vi can be prefaced by the
number of times you want the action to occur.
 For example, 2x deletes two character under the cursor location and
2dd deletes two lines the cursor is on.

PREP BY: TEKALIGN T. 135


Change Commands
 You also have the capability to change characters, words, or lines in
vi without deleting them.
 Here are the relevant commands:
Command Description
cc Removes contents of the line, leaving you in insert mode.
cw Changes the word the cursor is on from the cursor to the
lowercase w end of the word.
r Replaces the character under the cursor. vi returns to
command mode after the replacement is entered.
R Overwrites multiple characters beginning with the character
currently under the cursor. You must use Esc to stop the
overwriting.
s Replaces the current character with the character you type.
Afterward, you are left in insert mode.
S Deletes the line the cursor is on and replaces with new text.
After the new text is entered, vi remains in insert mode.

PREP BY: TEKALIGN T. 136


Copy and Paste Commands
You can copy lines or words from one place and then
you can past them at another place using following
commands:
Command Description

yy Copies the current line.

yw Copies the current word from the character the


lowercase w cursor is on until the end of the
word.
p Puts the copied text after the cursor.

P Puts the yanked text before the cursor.

PREP BY: TEKALIGN T. 137


Advanced Commands
 There are some advanced commands that simplify day-to-day
editing and allow for more efficient use of vi:
Command Description
J Join the current line with the next one. A count joins that
many lines.
<< Shifts the current line to the left by one shift width.

>> Shifts the current line to the right by one shift width.

~ Switch the case of the character under the cursor.


^G Press CNTRL and G keys at the same time to show the
current filename and the status.
U Restore the current line to the state it was in before the
cursor entered the line.
u Undo the last change to the file. Typing 'u' again will re-do
the change.

Refer for more from Handout

PREP BY: TEKALIGN T. 138


Word and Character Searching
 The vi editor has two kinds of searches: string and character.
 For a string search, the / and ? commands are used.
 When you start these commands, the command just typed will be
shown on the bottom line, where you type the particular string to
look for.
 These two commands differ only in the direction where the search
takes place:
o The / command searches forwards (downwards) in the file.
o The ? command searches backwards (upwards) in the file.
 The n and N commands repeat the previous search command in the
same or opposite direction, respectively.
 Some characters have special meanings while using in search
command and preceded by a backslash (\) to be included as part of
the search expression.

PREP BY: TEKALIGN T. 139


…con’t
Character Description

^ Search at the beginning of the line. (Use at the beginning


of a search expression.)

. Matches a single character.

* Matches zero or more of the previous character.

$ End of the line (Use at the end of the search expression.)

[ Starts a set of matching, or non-matching expressions.

< Put in an expression escaped with the backslash to find


the ending or beginning of a word.

> See the '<' character description above.

PREP BY: TEKALIGN T. 140


…con’t
 The character search searches within one line to find a
character entered after the command.
 The f and F commands search for a character on the
current line only.
 f searches forwards and F searches backwards and the
cursor moves to the position of the found character.
 The t and T commands search for a character on the
current line only, but for t, the cursor moves to the
position before the character, and T searches the line
backwards to the position after the character.

PREP BY: TEKALIGN T. 141


Set Commands
 You can change the look and feel of your vi screen using the following: set
commands.
 To use these commands you have to come in command mode then type :set
followed by any of the following options:
Command Description
:set ic Ignores case when searching
:set ai Sets autoindent
:set noai To unset autoindent.
:set nu Displays lines with line numbers on the left side.
:set sw Sets the width of a software tabstop. For example you would set a
shift width of 4 with this command: :set sw=4
:set ws If wrapscan is set, if the word is not found at the bottom of the
file, it will try to search for it at the beginning.
:set wm If this option has a value greater than zero, the editor will
automatically "word wrap". For example, to set the wrap margin
to two characters, you would type this: :set wm=2
:set ro Changes file type to "read only"
:set term Prints terminal type
:set bf Discards control characters from input

PREP BY: TEKALIGN T. 142


Running Commands
 The vi has the capability to run commands from within the editor.
 To run a command, you only need to go into command mode and type
:! command.
 For example, if you want to check whether a file exists before you try to
save your file to that filename, you can type :! ls and you will see the
output of ls on the screen.
 When you press any key (or the command's escape sequence), you are
returned to your vi session.
Replacing Text
 The substitution command (:s/) enables you to quickly replace words or
groups of words within your files.
 Here is the simple syntax:
:s/search/replace/g
 The g stands for globally.
 The result of this command is that all occurrences on the cursor's line
are changed.

PREP BY: TEKALIGN T. 143


IMPORTANT
Here are the key points to your success with vi −
o You must be in command mode to use commands. (Press
Esc twice at any time to ensure that you are in command
mode.)
o You must be careful to use the proper case (capitalization)
for all commands.
o You must be in insert mode to enter text.

PREP BY: TEKALIGN T. 144


Exercise: Using vi
 Using vi, enter the text:
A linux sysadmin called Pete
Typed all his commands with his feet
After “rm -r”, his toe hit a star,
A sysadmin no longer is Pete
 Save the text to the file limerick in your home directory
 Make the following changes:
o Change 'Pete' to 'Joe', (twice) and 'feet' to 'toe'
o Swap the first line with the last line. (Use cut-and-paste, don't
retype!)
o Delete the third line
 Save the result in the file junk (not to the limerick file)

PREP BY: TEKALIGN T. 145


Finding files with the find command
 The find command searches for files meeting specified criteria
o Name, owner, group, timestamps, permissions, size, etc.
 Find has a complicated syntax; the general framework is:

PREP BY: TEKALIGN T. 146


Some examples of using find
 Show all files ending in '.c' in (and below) the current directory
$ find . -name '*.c'
 Find all files under /home owned by tux
$ find /home -user tux
 Find ordinary files in /usr/bin which are bigger than 1 Mbyte
$ find /usr/bin -type f -size +1000k
 Find all ordinary files owned by root which have zero length
$ find / -type f -user root -size 0 2> /dev/null

PREP BY: TEKALIGN T. 147


Exercise: Using find
List all the directories under /home that belong to dilbert

How many symbolic links are there under /usr/bin?

Does root own any zero-length regular files? How many?


o Hint: don't count them yourself!

What is the largest file in the file system?


o Hint: it is bigger than 10 Mbytes

PREP BY: TEKALIGN T. 148


Built-in Help
 Most of the GNU command line tools have built-in help, using the
--help option
tux@earth:~> cat --help
Usage: cat [OPTION] [FILE]...
Concatenate FILE(s), or standard input, to standard output.
-A, --show-all equivalent to -vET
-b, --number-nonblank number nonblank output lines
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-n, --number number all output lines
-s, --squeeze-blank never more than one single blank line
-t equivalent to -vT
-T, --show-tabs display TAB characters as ^I
-u (ignored)
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
--help display this help and exit
--version output version information and exit
With no FILE, or when FILE is -, read standard input.

PREP BY: TEKALIGN T. 149


End
PREP BY: TEKALIGN T. 150

You might also like