1736405993-Linux Notes
1736405993-Linux Notes
UNIT I
LINUX OPERATING SYSTEM
INTRODUCTION
Operating system:
⮚ An operating system (OS) is a program that acts as an interface between a user and a computer by
accepting input from the user, interpreting the input and generating output.
⮚ The OS manages computer hardware and system resources such as memory and hard disk.
⮚ The OS forms the base on which any application software is developed.
Some popular operating systems are:
● Linux
● Unix
● MSDOS
● MS windows 95/98
● MS windows NT server 4.0
● Apple max
1. Command Interpretation
The CPU interprets commands entered by a user to perform tasks such as copying or deleting files.
The OS translates the command to binary code so that the CPU can interpret the command.
Note :The CPU can interpret only binary code which comprises of 0’s and 1’s.
2. Process Management
A process operating system is defined as a program in execution.
To run a program needs to be in the main memory called RAM.
When you run a program the OS loads the program in the memory and the CPU executes one
instruction at a time.
In a multi programming environment many process run on the computers (at the same time) or
simultaneously, where the CPU time is divided.
The OS allocates time slots to the different processes in the memory which facilitates process
execution.
3. Memory Management
1
Stores the processes that are not being executed The OS allocates the available memory to the
processes.
As the main memory is limited, it is not possible to load all the processes at a given time.
The main memory stores the processes that ate currently running and the hard disks.
The hard disk is used as a temporary storage device.
Processes can be run only when they are in the main memory and theme the OS maps the
processes from the hard disk to the main memory.
5. File Management
Another X, feature of an OS is file management. The OS enables you to perform file operation
such as creating, naming, opening, reading and closing a file.
Types of Systems
i) Single User Systems
ii) Multi User Systems
i) Single User Systems
A single user system can only be used by one person at a time.
An example of a single user system is a personal computer (PC).
The PC is a popular single user system which is small, general purpose computer that can run
program to perform a wide variety of tasks.
Due to the low cost of the hardware requirements and a wide range of available software, the PC
has become very popular.
Single User Operating Systems:
MSDOS is an e.g. of single user OS which has a command line interface (CLI).
Note:
A CLI display data character by character and is only text based. A GUI display text as well as icons
and images. GUI based software is slower than CLI but is more user friendly.
Users can use the system console or terminal to connect to the multi user system.
Remote users can use communication lines of a telephone and connect to a multi users system.
Many users can share a printer connected to a multi user system.
2
The CPU of a multi user system is more powerful than that of a single user system.
Two essential features of multi user system are multi programming and multi tasking. For example,
having a cup of coffee, reading a book and talking to a friend over the phone, i.e. performing more than
one task simultaneously. However at a given time, either one could sip coffee, read the book or speak over
the phone by dividing time into smaller units and in each unit of time one task is done. Similarly the CPU
divides the time between all the active tasks.
A multiuser system consists of a computer with several terminals attached which enables various
users to work on the computer.
Note : The hard disk usually has the capacity to store a large amount of data because many users share
a multi user system.
Note : windows 95 is a multitasking OS but not a multi user system. It can run simultaneously run
multiple tasks, but it does not allow multiple user to connect to do all a given time.
3
● In 1992, the Linux Kernel was combined with the incomplete GNU system to form a
completely free OS .
● This OS called GNU/Linux is a combination of GNU and Linux .
● The GNU/Linux OS is commonly referred to as Linux OS.
Linux follows the open development model. Therefore the current development version of Linux is
always available open to users. Users can also suggest modifications to the kernel code. When a new
version of Linus Torvalds ensures strict quality control and then merges all the new code into the kernel.
This is an contrast to a closed model in which a project team develops a particular software version and
waits before users can work on softwares and report bugs. The project team then fixes the bugs and
releases a new version. This is the major reason for the success of Linux. Linux has an official mascot –
the Linux penguin – called tux. Linux has free software such as text editors browsers and programming
tools.
LINUX ARCHITECTURE
The GNU/Linux OS consists of a kernel, a shell, utilites and apply programs.
The architecture of the Linux OS is displayed in Figure 1.1.
KERNEL
HARDWARE
KERNEL :
The core of the Linux system is the kernel which is also the operating system program. The kernel
controls the resources of a computer allocating them to different users and tasks. It interacts directly with
the hardware, making programs easy to write and portable across different hardware platform. However
4
the users do not interact directly with a kernel. Instead the logon process initiates a separate, interactive
program called the shell for each user.
SHELL :
Linux has a simple user interface called the shell. The shell provides services for the user. A user
interacts with the computer by using the shell. The user need not know about the intricate details of the
hardware. Some common shells in Linux are bash, sh, tcsh, csh and ksh.
Multiprogramming :
Time sharing :
5
Multiprogramming is possible on the Linux system due to the concept of time sharing. In time
sharing, the OS manages various programs simultaneously. Programs are queued and CPU time for
specific period and it is then replaced in the queue.
Multitasking :
A program in Linux is broken down into tasks such as reading from or writing to the disk or
waiting for input from a user. The ability of any OS to handle the execution of multiple tasks is known as
multi tasking .
When a task is waiting for the completion of another task, the CPU, instead of waiting time, starts
executing the next task. Therefore while one task is waiting for input from the user, another task could be
reading from the hard disk. The kernel is responsible for scheduling the tasks. The amount of physical
memory might not always be sufficient to execute large apply or enable multiple apply to be active at a
given time.
In such situation a partition that is a logical position of the hard disk can be utilized as artificial or
virtual memory. That is the OS places the programs and data which are not frequently used in this portion
of the hard disk and loads them in the memory whenever required.Therefore the OS uses the resources of
the computer optimally.
Utilities :
● Samba
● Cron scheduler
● Licencing
● Web server .
Samba :
● The name samba is derived from the server message block protocol or SMB.
● SMB is the protocol used by Microsoft OSs to share files and printers.
● Samba is a suit of programs that implement the SMB protocol on Linux
● Using samba Linux file system can be shared with windows 95, windows 98 or windows
NT.
● Also you can also share a windows 95/98/NT file system with linux.
● Similarly, SMB can be used to share printers connected to windows 95/98 NT computers
with Linux.
1. Note : A Protocol is a set of rules that specify the communication standards for data transfer.
2. A file system is a mechanism used by an OS to store and manage files and directories on a
storage medium.
Cron scheduler :
▪ Linux has a scheduler program called cron.
▪ Cron is used to run commands, scripts or programs at scheduled times.
Licensing :
▪ Linux is licensed under the GNU general public license.
▪ The licensing for red hat linux states that a person can make any number of copies
of software and distribute it freely or charge a price for it.
6
▪ Linux can also be downloaded free of cost from the internet.
Web server :
● Web server is a process that runs on the OS and enables users to access resources
that have been published in the form of web pages.
● A web server can enable users to access resources on a wide area network (WAN )
or the internet.
● A web server is commonly referred to as a computer that delivers web pages.
● Linux OS comes with the apache web server.
● For example : when the address of a web site is typed say www.apache.org in a web
server, the apache web server sends the home page of the web site to your
computer.
▪ Bourne shell
▪ C shell
▪ Korn shell
▪ Restricted shell
▪ Bash shell
▪ Tcsh shell
▪ A shell
▪ Z shell
1) Bourne shell
o The Bourne shell was developed by Stephen R .Bourne at AT & T and named after the developer,
Bourne.
o The Bourne shell is distributed in all the UNIX systems and is stored in the /bin directory.
o The executable file name for Bourne shell is sh which is one of the most widely used shells for
UNIX systems.
2) C Shell
o The C shell was developed by William Joy at the University of California at Berkeley to provide
a programming interface similar to the c programming language.
o The executable file name for C shell is csh.
o The C shell derives its name from its programming language which resembles the C
programming language in syntax.
3) Korn Shell
o The Korn Shell, developed by David Korn at AT&T and named after him.
o The Korn Shell combines the features of bourne shell and C shell.
o The executable file name for the korn shell is ksh .
4) Restricted shell :
o To provide limited access on the OS to a user, the restricted shell can be used.
o Used for guest users to provide limited rights and permissions.
o In addition, the restricted shell is used to restrict the users of the OS to a limited
environment.
5) Bash shell :
o The bash shell is an enhancement on the bourne shell.
7
o Bash is an acronym for Bourne Again Shell.
o Bash is a product of Free Software Foundations GNU project the bash shell is the
default shell for most Linux systems and stored in the / bin directory.the bash shell
stores all the commands that is used in a session.
o In addition the bash shell also stores the commands used in the previous sessions.
o In red hat Linux the sh command is a symbolic link to bash.
6) Tcsh shell :
o Tcsh stands for tom’s C shell and is an enhancement of the C shell.
o The Tcsh shell is also known as the TC shell.
o In Linux, the csh command is symbolic link to the Tcsh shell.
o To execute the TC sh shell type either csh or Tcsh at the command prompt
7) A shell :
o The A shell was developed by Kenneth Almquist of the University of Berkeley.
o It emulates the bourne shell
o The A shell is suitable for computers with limited memory.
o The executable file for A shell is ash.
8) Z shell :
o The Z shell offers the features of Tcsh and Korn shells.
o In addition, it provides a large number of utilities and extensive documentation.
o The executable file name for the Z shell is Zsh.
The telnet program is used to connect to a computer running the Linux operating system
from a computer running windows 95/98/NT operating systems .
To launch the telnet program type the following command at the command prompt
telnet <host name or IP address >
for example: to connect a working computer running the windows 95 OS and the TCP/IP address
assigned to the Linux server were 192.168.0.1 then give the folly, command to connect to the
Linux server.
telnet 192.168.0.1
after connecting to the Linux server, the folly message appears on the screen.
Red hat Linux server 7.1( sea wolf ) kernel 2.4 2-2 o an 686 login :
Logon :
Each user has an identification called the user name or the logon name. The logon name is entered
by the user when the login: prompt appears on the screen.
8
Note: when a user enters the logon name and password, the user name and password are checked
in shadow and password files.
If the login : information provided by the user does not match the information in the shadow and
password files, an error message” login incorrect “ is displayed. Thus, this check ensures that only
authorized users access the system.
When a valid user name and password are entered, the shell prompt is displayed on the screen as
given below.
user_name@ localhostcurrent_directory_name.
$ is the shell prompt.
At the shell prompt, the user_name is the logon nae of the user and current_directory_name is the
current working directory of the user.
When a user logon account is created, the administrator assigns a home directory to the user.
Unit II
Unix uses a hierarchical structure for organizing files and directories. This structure is often referred to as
a directory tree. The tree has a single root node, the slash character (/), and all other directories are
contained below it.
Home Directory
The directory in which you find yourself when you first login is called your home directory.
You will be doing much of your work in your home directory and subdirectories that you'll be creating to
organize your files.
You can go in your home directory anytime using the following command −
$cd ~
$
Here ~ indicates the home directory. Suppose you have to go in any other user's home directory, use the
following command −
$cd ~username
$
$cd –
$
9
Absolute/Relative Pathnames
Directories are arranged in a hierarchy with root / at the top. The position of any file within the hierarchy
is described by its pathname.
/etc/passwd
/users/sjones/chem/notes
/dev/rdsk/Os3
A pathname can also be relative to your current working directory. Relative pathnames never begin with /.
Relative to user amrood's home directory, some pathnames might look like this −
chem/notes
personal/res
To determine where you are within the filesystem hierarchy at any time, enter the command pwd to print
the current working directory −
$pwd
/user0/home/amrood
Listing Directories
To list the files in a directory, you can use the following syntax −
$ls dirname
Following is the example to list all the files contained in /usr/local directory −
$ls /usr/local
Creating Directories
We will now understand how to create directories. Directories are created by the following command −
$mkdir dirname
Here, directory is the absolute or relative pathname of the directory you want to create. For example, the
command −
10
$mkdir mydir
$
Creates the directory mydir in the current directory. Here is another example −
$mkdir /tmp/test-dir
$
This command creates the directory test-dir in the /tmp directory. The mkdir command produces no
output if it successfully creates the requested directory.
If you give more than one directory on the command line, mkdir creates each of the directories. For
example, −
Creates the directories docs and pub under the current directory.
$mkdir /tmp/amrood/test
mkdir: Failed to make directory "/tmp/amrood/test";
No such file or directory
$
In such cases, you can specify the -p option to the mkdir command. It creates all the necessary directories
for you. For example −
$mkdir -p /tmp/amrood/test
$
Removing Directories
Directories can be deleted using the rmdir command as follows −
$rmdir dirname
$
Note − To remove a directory, make sure it is empty which means there should not be any file or sub-
directory inside this directory.
Changing Directories
You can use the cd command to do more than just change to a home directory. You can use it to change to
any directory by specifying a valid absolute or relative path. The syntax is as given below −
$cd dirname
$
Here, dirname is the name of the directory that you want to change to. For example, the command −
$cd /usr/local/bin
$
Changes to the directory /usr/local/bin. From this directory, you can cd to the directory
/usr/home/amrood using the following relative path −
$cd ../../home/amrood
$
Renaming Directories
The mv move
represents the directory one level above the current working directory, often referred to as the parent
directory.
If we enter the command to show a listing of the current working directories/files and use the -a option to
list all the files and the -l option to provide the long listing, we will receive the following result.
$ls -la
12
drwxrwxr-x 4 teacher class 2048 Jul 16 17.56 .
drwxr-xr-x 60 root 1536 Jul 13 14:18 ..
---------- 1 teacher class 4210 May 1 08:27 .profile
-rwxr-xr-x 1 teacher class 1948 May 12 13:42 memo
$
File management in Unix/Linux : All data in Unix is organized into files. All files are organized into
directories. These directories are organized into a tree-like structure called the filesystem.
When you work with Unix/Linux, one way or another, you spend most of your time working with files.
● Ordinary Files − An ordinary file is a file on the system that contains data, text, or program
instructions. In this tutorial, you look at working with ordinary files.
● Directories − Directories store both special and ordinary files. For users familiar with Windows or
Mac OS, Unix directories are equivalent to folders.
● Special Files − Some special files provide access to hardware such as hard drives, CD-ROM
drives, modems, and Ethernet adapters. Other special files are similar to aliases or shortcuts and
enable you to access a single file using different names.
Listing Files
To list the files and directories stored in the current directory, use the following command −
$ls
$ls
The command ls supports the -l option which would help you to get more information about the listed files
−
$ls -l
total 1962188
● First Column − Represents the file type and the permission given on the file. Below is the
description of all type of files.
● Second Column − Represents the number of memory blocks taken by the file or directory.
● Third Column − Represents the owner of the file. This is the Unix user who created this file.
● Fourth Column − Represents the group of the owner. Every Unix user will have an associated
group.
● Fifth Column − Represents the file size in bytes.
● Sixth Column − Represents the date and the time when this file was created or modified for the
last time.
● Seventh Column − Represents the file or the directory name.
In the ls -l listing example, every file line begins with a d, -, or l. These characters indicate the type of the
file that's listed.
Metacharacters
Metacharacters have a special meaning in Unix. For example, * and ? are metacharacters. We use * to
match 0 or more characters, a question mark (?) matches with a single character.
For Example −
$ls ch*.doc
Displays all the files, the names of which start with ch and end with .doc −
Here, * works as meta character which matches with any character. If you want to display all the files
ending with just .doc, then you can use the following command −
$ls *.doc
14
Hidden Files
An invisible file is one, the first character of which is the dot or the period character (.). Unix programs
(including the shell) use most of these files to store configuration information.
$ ls -a
Creating Files
You can use the vi editor to create ordinary files on any Unix system. You simply need to give the
following command −
$ vi filename
The above command will open a file with the given filename. Now, press the key i to come into the edit
mode. Once you are in the edit mode, you can start writing your content in the file as in the following
program −
Once you are done with the program, follow these steps −
You will now have a file created with filename in the current directory.
$ vi filename
$
15
Editing Files
You can edit an existing file using the vi editor. We will discuss in short how to open an existing file −
$ vi filename
Once the file is opened, you can come in the edit mode by pressing the key i and then you can proceed by
editing the file. If you want to move here and there inside a file, then first you need to come out of the edit
mode by pressing the key Esc. After this, you can use the following keys to move inside a file −
So using the above keys, you can position your cursor wherever you want to edit. Once you are
positioned, then you can use the i key to come in the edit mode. Once you are done with the editing in
your file, press Esc and finally two keys Shift + ZZ together to come out of the file completely.
$ cat filename
This is unix file....I created it for the first time.....
I'm going to save this content in this file.
$
You can display the line numbers by using the -b option along with the cat command as follows −
$ cat -b filename
1 This is unix file....I created it for the first time.....
2 I'm going to save this content in this file.
$
$ wc filename
2 19 103 filename
$
You can give multiple files and get information about those files at a time. Following is simple syntax −
Copying Files
To make a copy of a file use the cp command. The basic syntax of the command is −
$ cp source_file destination_file
$ cp filename copyfile
$
You will now find one more file copyfile in your current directory. This file will exactly be the same as
the original file filename.
Renaming Files
To change the name of a file, use the mv command. Following is the basic syntax −
$ mv old_file new_file
The following program will rename the existing file filename to newfile.
$ mv filename newfile
$
The mv command will move the existing file completely into the new file. In this case, you will find only
newfile in your current directory.
Deleting Files
To delete an existing file, use the rm command. Following is the basic syntax −
$ rm filename
Caution − A file may contain useful information. It is always recommended to be careful while using this
Delete command. It is better to use the -i option along with rm command.
Following is the example which shows how to completely remove the existing file filename.
$ rm filename
$
Multiple files can be removed at a time with the command given below :
17
$ rm filename1 filename2 filename3
$
NAME
SYNOPSIS
rm [OPTION]... FILE...
DESCRIPTION
If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --
recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the
response is not affirmative, the entire command is aborted.
Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or
the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the
response is not affirmative, the file is skipped.
OPTIONS
TAG DESCRIPTION
-f, --force ignore nonexistent files, never prompt.
-i prompt before every removal.
prompt once before removing more than three files, or when removing
-I recursively. Less intrusive than -i, while still giving protection against most
mistakes.
prompt according to WHEN: never, once (-I), or always (-i). Without WHEN,
--interactive[=WHEN]
prompt always.
when removing a hierarchy recursively, skip any directory that is on a file
--one-file-system
system different from that of the corresponding command line argument.
--no-preserve-root do not treat '/' specially.
--preserve-root do not remove '/' (default).
-r, -R, --recursive remove directories and their contents recursively.
-v, --verbose explain what is being done.
--help display this help and exit.
--version output version information and exit.
18
Wildcard Characters
The shell interprets these special characters, also known as wildcard characters, as a specific
pattern of characters. The shell then compares all the file names under the directory specified in the
command to locate file names that match the pattern. The command is executed on files whose names
match the pattern.
Character Purpose
* Matches none or one character or a string of characters.
? Matches exactly one character.
[] Matches exactly one of a specified set of characters.
The * Wildcard
The shell interprets the *wildcard as a string of none, one or more characters.
The ? Wildcard
The shell interprets the ? wildcard as a string of exactly one occurrence of any character.
The above command displays all the files that contain any character(s) before a period, followed by a
single character after a period.
The [ ] Wildcard
The above command displays the contents of files with two character file names starting with a and with
the next character as 1, 2 or 3 such as a1, a2 and a3.
EXAMPLES
Example-1:
Remove the file myfile.txt. If the file is write-protected, you will be prompted to confirm that you really
want to delete it:
19
$ rm myfile.txt
Example-2:
Remove the file myfile.txt. You will not be prompted, even if the file is write-protected; if rm can delete
the file, it will:
$ rm -f myfile.txt
Example-3:
Remove all files in the working directory. If it is write-protected, you will be prompted before rm removes
it:
$ rm *
Example-4:
Remove all files in the working directory. rm will not prompt you for any reason before deleting them:
$ rm -f *
Example-5:
Attempt to remove every file in the working directory, but prompt before each file to confirm:
$ rm -i *
Example-6:
Remove every file in the working directory; prompt for confirmation if more than three files are being
deleted:
$ rm -I *
Example-7:
Remove the directory mydirectory, and any files and directories it contains. If a file or directory that rm
tries to delete
is write-protected, you will be prompted to make sure that you really want to delete it:
$ rm -r mydirectory
Example-8:
Same as the above command, but you will never be prompted; if rm can delete the files, it will:
$ rm -rf mydirectory
20
UNIT – III
22
The following table lists out the basic commands to use the vi editor −
1 vi filename
Creates a new file if it already does not exist, otherwise opens an
existing file.
2 vi -R filename
Opens an existing file in the read-only mode.
3 view filename
Opens an existing file in the read-only mode.
Following is an example to create a new file testfile if it already does not exist in the current working
directory −
$vi testfile
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 non-viewable character present.
The vi editor works in two modes, edit and command. The edit mode is used to add text to a file.
The vi editor has different commands to add, change, and delete text.
23
The command mode is used to move the cursor, save the file, and give various commands to
manage files.
To switch from edit mode to the command mode, press the <Esc> key. To switch from the
command mode to the edit mode, press a, A, o, O, i, or I keys.
10 :r<filename><Enter> Reads and inserts the contents of the file after the
current line.
24
Insert and Replace Commands
The following table describes the commands used to insert and replace text in the vi editor:
5 o Creates a new line for text entry below the cursor location
6 O Creates a new line for text entry above the cursor location
25
Word Movement Commands
The word movement commands are:
1 dw Deletes a word.
2 dd Deletes a line.
3 cw Changes a word.
4 cc Changes a line.
6 J Join lines.
26
1 yy or Y Yanks the current line, which is to be copied.
To copy 20 lines of text from a file, give the 20yy command. The 20yy command will copy 20
lines of text starting from the current line.
Pattern – Finding Commands
The pattern – finding commands in the vi editor are:
1 fx Finds the specified character, x, on the current line after the current
cursor position.
Managing Documents
Locating Files in Linux
The find Command
The find command is used to locate a file in a specific directory and all in its subdirectories.
Syntax
find [path] [expression]
The find command, specify the path where the files are located. The expression consists of options that
affect the execution of the find command. Some of the options of the find command are:
The –name Option
The –name option to specify the name of the files that to be located.
27
Example
$ find / home / Steve -name “jan”
/ home / Steve / 2000 / jan
/ home / Steve / 2001 / jan
Here, / home / Steve is the name of the directory in which specific files need to located. The
–name “jan” option specifies that all the files with the name jan are to be located.
root
Steve
d J f t d J f t t
a e e a e e e
f n b m f n b m m
p p p
29
Standard Files
Standard output
Utility
Standard error
Standard Input
A computer system consists of mainly three parts, input, processing, and output devices. The input
device accepts data from a user, and the output device displays or prints information or any error messages
that are generated. The processing device processes the user input according to the specified instructions
to generate the desired output.
The keyboard and mouse are examples of input devices, and the screen and the printer are the
examples of output devices. The CPU is the processing device.
In the Linux operating system, all input and output devices are considered special files.
Standard Input File
In Linux, the input is used to execute a command; the shell interprets the command and assigns the
keyboard as the default source of input. The keyboard is referred to as the standard input file.
If we specify the cat command with a file name, all the lines in the file are displayed. However,
without a file name, the cat command takes input from the standard input file or the keyboard as given
below:
$ cat <Enter>
The cat command waits for input from the keyboard. The screen will display the following output:
$ cat <Enter>
This is a test to depict <Enter>
This is a test to depict
While using the cat command, we can enter multiple lines. To indicate the end of input, press <Ctrl> and
d keys. The $ prompt is then displayed on the screen.
In Linux, all the open files, including standard files, are assigned a number called the file descriptor. The
standard input file is assigned the file descriptor 0.
Standard Output File
The shell assigns the screen as the default destination for the output of any command that is
executed. The screen is referred to as the standard output file.
Example:
$ ls
The shell executes the command and sends the output, the directory list, to the standard output file or the
screen. The standard output file is assigned the file descriptor 1.
Standard Error File
30
When a user types invalid or unauthorized commands, such as commands for which a user does
not have permission, the shell utilities display error messages on the screen. The screen is referred to as
the standard error file. This is assigned to the file descriptor 2.
Execute the cat command by a file name that does not exist, an error message is displayed on the
screen.
Error messages are displayed on the standard error file if you do not have appropriate permissions
on a file.
A user logs on to the Linux server and types the following command:
$ cp file1 dir1
The command is correct; it might generate error if the user does not have the write permission on
dir1 or the read permission on file1.
Redirection
The process of changing the assignment for the standard input, the standard output and the
standard error file is known as redirection.
Using redirection, input to a command can be taken from a file instead of the keyboard. Similarly,
the output of a command or error can be written to a file or printed instead of being displayed on the
screen. The three types of redirection are:
● Input
● Output
● Error
Input Redirection
The symbol for redirecting the input is <. We can redirect the input from a file instead of typing
the commands by using the keyboard.
Example
$ cat < test1 <Enter>
The < symbol implies input redirection from the file test1 on the hard disk. The cat command reads each
line of the file test1 as input and displays it on the screen. By specifying the input redirection, the standard
input is received from a disk file instead of the standard input file. The file descriptor can be using for the
above command as:
$ cat 0 < test1 <Enter>
Here, 0 indicates input redirection.
Output Redirection
The symbol for redirecting the input is >. To store the output of the ls command in another file instead of
displaying the output on the screen, you need to redirect the output to a file.
Example
$ cat test1 > test2
31
The > symbol implies redirection of the output to the file test2. The output of the cat command is
written to a disk file test2.
In output redirection, the file to which the output is redirected is first created on the disk as an
empty file before the output is sent to the file. However, if the file exists, its contents are deleted before
the output is written to it.
To add the output of a command at the end of a file instead of overwriting the existing contents of
the file. To append the output to the file test2, the following command is used:
$ cat test1 >> test2
The file descriptor can be used as follows:
$ cat test1 1> test2 and
$ cat test1 1>> test2
Here,1> indicates output redirection. Although the file descriptor 1 is not necessary, can include it in the
command for clarity.
Error Redirection
The following example explains error redirection:
$ cat datafile 2> error-msg <Enter>
Assume that the file datafile does not exist in the current directory. When a user tries to execute
the above command, Linux generates an error message because the execution is unsuccessful. In this case,
the error message will not be displayed on the screen (the standard error file); instead the message will be
written to the file error-msg.
Just like output redirection, error redirection first creates the file to which the error messages are
redirected and then writes the error output to the file.
FILTERS
A filter is a program that takes input from the standard input file, processes it, and sends the output
to the standard output file. Linux provides various filters, such as cat, grep, wc, tr, and cut, to enable to
work effectively with data.
The grep Filter
The grep filter searches a file for a specified pattern of characters and displays all the lines that
contain the pattern. The pattern that is searched for is referred to as a regular expression. The grep filter
cannot be used without specifying a regular expression.
Syntax:
grep regular_expression [filename]
32
The filename is optional in the grep command. If we do not specify a file name, the grep filter excepts
input from the standard input file. While typing text, grep searches the line for the regular expression and
displays the line if it contains the specified expression. To stop the execution of the grep filter, press the
<Ctrl> and d keys.
Example:
$ grep job <Enter>
work
job
job
task
<Ctrl> d
In this example, the grep filter waits for input from the standard input file. The grep filter searches
for the word job when you enter the words work, job and task. When the grep filter locates the word job, it
displays the word job again on the standard output file. Notice that the word job appears two times in the
output.
Character Use Example Description
[ ] Matches any one of a set grep “New[abc]” Specifies the search pattern as
of characters. filename ‘Newa’, ’Newb’, or ‘Newc’.
[ ] with Matches any one of a grep “New[a-c]” Specifies the search pattern as
hyphen range of characters. filename ‘Newa’, ’Newb’, or ‘Newc’.
^ Matches the pattern grep Specifies the search pattern as
following it if the pattern “^New[abc]” ‘Newa’, ’Newb’, or ‘Newc’
occurs at the beginning of filename where the patter must occur at the
a line. beginning of a line.
^ within [ ] Matches the pattern that grep “New[^a- Specifies a pattern containing the
does not contain any c]” filename word ‘New’ followed by any
character in the specified character other than ‘a’, ‘b’, or
set. ‘c’.
$ Matches the pattern grep Specifies the search pattern as
preceding it if the pattern “New[abc]$” ‘Newa’, ’Newb’, or ‘Newc’
occurs at the end of each filename where the patter must occur at the
line. end of a line.
33
(dot) Matches any one grep Specifies a pattern containing the
character. “New.[abc]” word ‘New’ followed by any
filename character, followed by ‘a’, ‘b’, or
‘c’.
\ Ignores the special grep Specifies the search pattern, as
(backslash) meaning of the “New\.\[abc\]” New.[abc].The special meaning
filename of the dot, the opening bracket,
and closing bracket is ignored.
Options of the grep Filter
The grep filter offers options that enable to alter the output of the command. The options available with
the grep filter are as follows:
● -n : this option is used with the grep filter to display each line matching the specified pattern, along
with the line number. The line number is printed at the beginning of the line.
● -c : this option is used to display only a count of the lines that match the specified pattern.
● -v : this option is used to display all the lines that do not match the specified pattern.
The options are specified before the regular expression.
The wc Filter
The wc filter is used to count the number of lines, words, and characters in a file. It is also used in
standard input file.
Syntax
wc [ - lwc] [filename/s ]
Example
$ wc sample <Enter>
2 7 29 sample
The file sample has 2 lines, 7 words, and 29 characters.
The following table explains the options of the wc filter:
Option Function
34
Similar to the grep filter, might or might not specify the filename with the wc filter. If do not specify a file
name with the wc filter, it excepts input from the standard input file, as shown below:
$ wc <Enter>
Wc is a filter
<Press Enter>
<Press Ctrl and d>
1 4 15
After typing the text, wc is a filter, and press the enter key, the wc filter counts the number lines, words,
and characters that have entered. The wc filter displays the number of lines, words, and characters entered
when the execution stops. As in the case of the grep filter, use the <Ctrl> and d keys to stop the execution
of the wc filter.
The cut Filter
The cut filter is used to extract specific columns from files. In addition, the cut filter is also used to extract
the output of certain commands, such as ls and who.
Syntax
cut [options] [filename/s]
The following table explains the options of the cut filter:
Option Function
Examples
$ cut –d ‘ : ‘ –f1 / etc / passwd
Root
Bin
Daemon
Adm
Lp
Sync
35
In the above example, the cut filter is used to extract only the names of the users in the / etc/ passwd file.
The field separator is the : symbol.
The tr Filter
The tr filter is used to replace one set of characters with another.
Example
$ tr ‘ : ‘ ‘ ‘ < / etc / passwd
The above command replaces each occurrence of the : symbol in the / etc / passwd with a space and
displays the output on the standard output file. It is also used to replace repeated occurrences of a
character with a single occurrence of the character.
The –s option of the tr filter to squeeze several occurrences of a character into one character.
$ who > temporary
$ tr –s “ “ < temporary
root tty1 Sep 28 17:02
steve pts/4 Sep 28 19:36 (172.17.55.167)
In the above example, the –s option of the tr filter works on each record and reduces multiple spaces with
a single space.
The tr filter is used to change the casting of letters.
Example
$ tr “ [a – z] “ “ [A – Z] “
The road was a ribbon of moonlight
THE ROAD WAS A RIBBON OF MOONLIGHT
The above command converts all lowercase letters to uppercase.
PIPES
In Linux, we can combine filters with other Linux commands, such as ls or more, so that the
standard output of one filter or command can be sent as standard input to another filter or command.
Example
$ ls > tempfile
$ more tempfile
Here, the ls command stores a list of the directories in the file tempfile. The tempfile file is then used as
input by the more command.
By using the Linux pipe feature, the above two steps can be combined and executed as a single command
without creating a temporary file, as shown below:
36
$ ls | more
The vertical bar ( | ) is the pipe character, which indicates that the output of the command typed before the
| is to be sent as input to the command typed after the |.
The pipe command can be used to perform complex tasks by combing the commands available in Linux.
When pipe command is used, specify multiple commands or filters. To understand how the pipe command
works, consider the example in the figure below:
Input Output
Is
more
numbers
sort -
Command1 Command2
37
The above command displays the contents of the file temp on the screen and also writes to the files temp1
and temp2.
Example:
$ sort numbers | tee sort – numbers | more
In the above command, the file numbers is sorted, and the sorted data is redirected to the tee
command. The tee command creates the file sort – numbers, and stores the data in the file. The tee
command also redirects data as input to the more utility.
The following figure depicts how the tee command works:
sort tee
numbers
38
UNIT – IV
● Other users
The permissions that can be granted or revoked are symbolically represented by the letters r, w, and x and
are grouped together as rwx for different users in Linux.
The permissions for a file or a directory are:
r – Indicates the read permission. It can be represented by the number 4.
w – Indicates the write permission. It can be represented by the number 2.
x – Indicates the execute permission. It can be represented by the number 1.
Access type Denoted by Action permitted on a file Action permitted on a directory
Read r Allows displaying copy Allows to list the contents of the
and compiling the file. directory
Write w Allow to edit, rename and Allows creating new files and
move the file to another subdirectories within this
location. directory.
Execute x Allows executing the file Allows to move to the specified
with the read permission. directory using the cd command
Viewing File Access Permissions
The ls command is used to display the names of files. The –l option with the ls command ,the
command displays the names of files with the date and time of creation, size, user name, group name, and
access permissions for the file.
Example:
[localhost]$ ls -l
Total 21
-rw-rw-r- 1 Steve Steve 134 Sep 21 10:48 DEADJOE
drwxr-xr-x 5 Steve Steve 1024 Sep 20 23:30 Desktop
drwxrwxr-x 2 Steve Steve 1024 Sep 21 22:56 tennis
39
FAP
_ r w z r - - r - -
The first character indicated the type of file, such as an ordinary file, a hidden file, or a directory.
The next set of three characters display the read, write, and execute permissions, in that order, for the file
owner. The following three characters are the permissions for the group owner, and the last three are the
permissions for other users.
If the permission is available, r, w or x is displayed; else a hyphen is displayed.
For directories, need to interpret FAPs as follows:
The read permission allows a user to:
● List the contents of a directory.
The write permission allows a user to:
● Copy files to a directory.
● Remove files from a directory.
● Rename the files in a directory.
● Make a subdirectory.
● Remove a subdirectory from the directory.
● Move files to and from the directory.
The execute permission allows a user to:
● Change to a directory.
● Display a file in a directory.
● Copy a file from a directory.
Changing File Access Permissions
The access permissions can be modified by associated with a file or a directory by using the chmod
command. However, only the owner of a file can change the permissions associated with it.
The chmod command can be used to grant or revoke permissions for files and directories.
40
The permissions for a file or directory indicate the actions that can be performed on the file or the
directory.
When using the chmod command, use the + sign to grant permissions, and the – sign to revoke
permissions.
The syntax for the chmod command is shown below:
chmod <mode> <filename>
The chmod command is to specify the mode (permission to a type of user) in the following ways:
● Symbolic – The permission and the user type are specified as symbols.
● Absolute – The permission is specified as a number.
The following command shows the use of the chmod command:
[localhost] $ chmod g+x trial.rpt
[localhost] $ chmod o-w cust.rpt
In the first example, the group owner is granted the permission to execute the file, trial.rpt. In the second
example, the permission to write to the cust.rpt file is revoked from other users.
Symbolic Mode
In the symbolic mode, the symbols are used to specify the permissions and the types of
users, such as file owner or others, to whom the permissions are to be granted or revoked.
The following table explains the symbolic representation of entities:
Symbol Meaning
a All users.
To modify the permissions for a file, the file owner must specify:
● The type of user for whom the permission is to be modified.
● The type of permission that is to be modified.
● Whether the permission is to be granted or revoked.
● The name of the file for which the permission is to be modified.
Linux allows changing FAPs for a specific user type. Some examples that demonstrate the use of FAPs:
[localhost] $ ls -l x.c
41
-rw-rw-r- 1 Steve IRDTECH 50 Sep 22 21:01 x.c
[loclhost] $ chmod u+x x.c
Here, ‘u’ indicates the file owner, ‘+’ indicates that the permission is to be given, ‘x’ indicates the execute
permission, and ‘x.c’ represents the file name.
After the above command is executed, the FAP for the file x.c will be modified as follows:
[localhost] $ ls -l x.c
-rw-rw-r- 1 Steve IRDTECH 50 Sep 22 21:01 x.c
To remove the read permission from the group owner, type the following command:
[localhost] $ chmod g-r x.c
Here, ‘g’ indicates the group owner, and ‘-‘ indicates that the permission is to be removed.
Absolute Mode
In the absolute mode, a series of digits is used to represent the file permissions. Using
the absolute mode is more convenient than using the symbolic mode because you can specify different
permissions for all the types of users in one statement.
The following table explains the number that denotes each type of permission:
Number Permission
4 Read
2 Write
1 Execute
Octal 7 6 4
Assign permissions by using the following command:
[localhost] $ chmod 664 - / * . txt
Here, the first octet is for the file owner, the second octet is for the group owner, and the third octet is for
other users.
42
The following explains some of the permissions that are allocated when specifying a particular absolute
mode with the chmod command:
chmod 644 file.htm
Set the permissions of file.htm to "owner can read and write; group can read only; others can read only".
Recursively (-R) Change the permissions of the directory myfiles, and all folders and files it contains, to
mode 755: User can read, write, and execute; group members and other users can read and execute, but
cannot write.
Set the permissions of file.cgi to "read, write, and execute by owner" and "read and execute by the group
and everyone else".
43
61 ------rw—x Assigns the execute permission to other
users and the read and write permissions
to group members.
741 -rwxr------x Assigns read, write and execute
permissions to the owner, only the read
permission to group users, and only the
execute permission to other users.
777 -rwxrwxrwx Assigns read, write and execute
permissions to the owner, group user and
other users.
The unmask Value
When you create a file, the unmask value and the mode value determine the initial file
permissions. The mode value indicates that all the users have read and write permissions for a file. By
default, the mode value is 666 for files and 777 for directories and executable files. To derive file access
permissions, the value of unmask is subtracted from the mode value.
By default, the unmask value is given as 002 for user and 022 for root user, which means that each
file that a user creates has a permission, 666 – 002 = 664 (rw-rw-r-).
The unmask value is specified in the /etc/profile file. The unmask command is used to print or
modify the unmask value of files and directories. To ensure that the default file access permissions are
same across the various sessions in Linux, the unmask command is stored in the .bash_profile file. When
a new Bash shell is created, the unmask command is executed automatically.
The syntax for the unmask command is:
unmask [ value ]
Here, value is an octal number of up to three digits. For example, if you specify a value 0f 77, the
unmask command is interpreted by the operating system as 077.
The following table depicts the effect on files that are created by using the various unmask values.
In the table, the unmask values are listed in decreasing order of security:
Value Used with the unmask Permission of the File Meaning
Command after the Command
066 -rw--------- Assigns read and write permission to a user and no
access for group or other users.
026 -rw-r-------- Assigns read and write permissions to a user; read
permissions to group and no access to other users.
44
006 -rw-rw------ Assigns read and write permissions to a user and group
but no access to other users.
022 -rw-r—r--- Assigns read and write permissions to a user, read
permissions to group; and read permission to other
users.
If the shell cannot locate a file corresponding to the command that you enter, the shell displays an error
message and then display the $ sign.
Example:
[ localhost ] $ lst file1
Bash: lst : command not found
[ localhost ] $
The echo Command
The echo command is used to display the messages on the screen.
Example:
$ echo “This is an example of the echo command”
This is an example of the echo command
$
The echo command displays text enclosed between “ “ on the screen. By default, the echo command
displays the text and then places a newline character at the end of it. The newline character moves the
cursor to the next line after the text is displayed. To keep the cursor on the same line, use –n option with
the echo command.
Example:
$ echo –n “This will keep the cursor on the same line”
The $ sign is displayed on the same line as the output.
Executing a Shell Script
Shell scripts can be used to automate tasks. The shell can read the file in which the commands are
stored and execute them. Such a file is called a script file.
To create a script file, need to write commands in a text file by using a text editor, such as the vi
editor. After creating the script file, need to execute it. The following file named magic that need to be
executed:
# ! / bin / bash
46
echo “This is my first bash script “
In the magic file, the first line of the file informs the shell to execute the script file by using the bash shell.
The other shell such as sh,tcsh, or ksh can also be used as a execute shells scripts. While creating a script
file, the # and ! characters should be the first two characters of the script file followed by the interpreter
that should be used to execute the file.
The magic file can be executed in the following ways:
1. At the command prompt, type:
$ bash magic
If there is an error in the first line of the shell script when it is executed, an error message “No such file or
directory” will be displayed. To resolve the problem, type the whereis bash command to locate the path of
the bash program, and use the path in the shell script.
2. At the command prompt, type:
$ chmod u+x magic Change FAP
$ ./magic Execute the shell script
To execute a shell script directly at the $prompt, need to change the FAPs for the script file. When you
log on to Linux, you begin work in a copy of the shell, known as the login shell. This shell is a utility.
Therefore, you can create a shell by executing the shell command. For example, to execute the bash
command to create the bash shell. The new shell is known as the subshell or child shell of the current
shell.
When executing a shell script directly at the $prompt, the current shell creates a child shell to
execute a shell script. The creation of the child shell ensures that the script does not affect the current
shell. The shell script is passed to the child shell for execution. The child shell is terminated as soon as the
shell script completes execution.
Example:
The following file is named hello:
# ! / bin / ksh
echo “Hello”
echo “World”
Change FAPs for the script file using the following command:
$ chmod u+x hello
$ ./hello
Hello
47
World
In the above example, the first line specifies that the shell script should be interpreted by using the Korn
shell (ksh).
Inserting commands
Can include comment entries in a shell script by prefixing statements with the # symbol. When the
shell encounters the # symbol, it ignores text following the # symbol in a line.
Example
# ! / bin / bash
echo “Hello”
# This is a comment line. This would not display any output.
echo “World”
In this example, the third line is a comment. The comment will be ignored by shell and no output will be
displayed. In a shell script, can add comments about the structure and working of the shell script for future
reference.
Variables
Creating Variables
Variables can be created at any point of time by simply assigning a value. A variable can be
created without a value by leaving the right-hand side of the assignment operator (=) blank. The syntax for
creating a variable is:
<variable name> = <value>
If the value is assign to the variable contains delimiter, such as an embedded space, it should be enclose
the value within either single or double quotes.
Example :
Name = “John Lennon”
However, need not use the quotation marks if the value does not have any embedded spaces.
In shell scripts, cannot declare variables as integers or characters. All the variables in the Linux operating
system are treated as character strings.
Example:
Name=Paul
Ctr=1
In the above example, ctr does not contain a numeric variable. The ctr variable contains a character.
Therefore, the ctr variable contains the character “1” and not the number 1.
48
Referencing Variables
The $ symbol is used to refer to the contents of a variable. For example, to assign the value of one
variable to another, use the following command:
variable1 = $(variable2)
In the above example, the value of variable2 is assigned to variable1.
The braces are used to delimit the variable name. For example, consider a variable named today
that contains the value 20 and another variable named x. Assign the value 20th to variable x by
concatenating the value of the variable today with the string th. To concatenate the values, you will use the
following command:
$ x = $(today)th
Now, x would contain the value 20th.
Reading a Value into a Variable
To assign a value to a variable, the shell specifies a value by using the keyboard. Enter the value
into a variable during the execution of a shell by using the read command.
$ read fname
The read command can be used at the shell prompt but is usually used in shell scripts. On execution, the
read command waits to enter a value for the variable. Press the <Enter> key after entering a value, the
remaining part of the shell script, if any, is executed. The read command does not prompt you to enter
data, can use the echo command to display a prompt.
$ echo “Enter your name”
Enter your name
$ read myname
Angela
In the above example, when the echo command is executed, a message is displayed. However, after the
read myname command is executed, the operating system waits for input. Enter Angela and press the
<Enter> key. The value, Angela, is stored in the variable myname. To display the value of the myname
variable by using the following command:
$ echo $myname
Angela
To store the names and phone numbers, you need to accept customer details, use the echo command to
prompt the user to enter data, use the read command to accept the values from the user. Finally, to store
the details in a file by using the >> operator.
The following shell script is used to store data and to accept details of customers:
49
#!/bin/bash
echo “Enter the name of the customer.”
read name
echo “Enter the mobile phone number.”
read number
echo “$name:$number”>>customerdata
Execute the storedata shell script by using the following command:
$ bash storedata
Alternatively, can acquire execute permission for the shell script and execute it as follows:
$chmod +x storedata
$ ./storedata
Local and Global Shell Variables
When a variable is referenced, only the shell that created it is aware of the variable. When a new
shell is created, it is unaware of the variables created in the parent shell. The same variable name can be
given a different value without the parent shell knowing about it. Such a variable is called a local variable.
When you create a variable, it is accessible only in the shell in which you create it. The subshells
or the parent shell of the current shell cannot access the variables of the current shell.
The following example explains the concept of a local variable:
$ continent=Africa
$ echo “$continent”
Africa
$ sh Creates a child shell
$ echo “$continent”
There is no response
$ continent=Asia Gives a new value, Asia to continent
$ echo “$continent”
Asia
Press <Ctrl> d
$ exit Displays exit and returns to the parent shell
$ echo “$continent”
Africa Parent is unaware of Asia
$ sh Creates another child shell
$ echo “$continent”
Continent does not have any value
Press <Ctrl> d
$ exit Displays exit and returns to the parent shell
$-
It is necessary for the child shell to know about the variables of the parent shell. The bash shell offers the
export command that enables the child shell to access the variables of the parent shell. Any shell variable
given as an argument to the export command is passed on to all subsequent child shells. A variable that is
50
made available to all the child shells of a shell is known as an exported variable. Consider the following
commands:
$ continent=Africa
$ export continent
$ echo “$continent”
Africa
$ sh Creates a new child shell
$ echo “$continent”
Africa Child shell has the variable continent
$ continent=Asia Gives a new value to continent
$ echo “$continent”
Asia
Press <Ctrl> d
$ exit Displays exit and returns to the parent shell
$ echo “$continent”
Africa Parent shell continues to have the value Africa
$-
In the commands given above, the last two commands show that variables can be exported or
passed on to child shells, but the opposite is not possible. The export command creates a copy of the
variable name and values and passes the copy to a child shell. The child shell can modify the value of the
copy of the variable. When the child shell terminates, the copy of the variable also ceases to exist. The
export command is used to pass on a variable to child shells, the original variable remains unaffected.
The variables created in a shell are local to the shell. In other words, variables created in a shell are
available only in the shell in which to create variables. The export command is used to make a variable
global or accessible to child shells.
Environment Variables
In a multiuser operating system, such as Linux, each user works on a copy of the shell. Each shell
has a set of special variables called environment variables, which users can edit to configure the shell’s
environment. By changing the values of environment variables, a user can customize the environment.
Some examples of environment variables are HOME, PATH, PS1, PS2, LOGNAME, SHLVL, and SHELL.
The HOME Variable
In the Linux operating system, each user has an associated directory called the home directory.
When a user logs on, by default, the user is taken to the corresponding home directory. The location of the
home directory of a user is stored in the environment variable HOME. For example, if the home directory
for the user Roger is /home/Roger, then the variable HOME will contain this value.
Example :
$ echo $HOME
The PATH Variable
51
The PATH variable contains a list of colon-delimited path names of directories that are to be
searched for an executable program. For example, the following command specifies that the directories to
be searched for any executable or command are /usr/bin and /bin, in that order:
$PATH = /usr/bin:/bin
The Linux operating system does not search the current directory. Only the directories specified in the
PATH variable are searched. To search the current directory, specify the path of the current directory in
the PATH variable. To specify the current directory in PATH variable a period is used.
Example:
a. PATH = /bin: /usr / bin : . – Searches in the order : /bin, /usr / bin, and the current directory.
b. PATH= . : bin : /usr/bin – Searches in the order : the current directory, / bin and / usr / bin
c. PATH = /bin : . : /usr/bin - Searches in the order : /bin, the current directory and / usr / bin
While executing a file, the Linux operating system is searched in the order specified in the PATH variable.
The PS1 Variable
The PS1 or Prompt String 1 variable contains the shell prompt, the $ symbol. The shell prompt can
be changing by editing the value of the PS1 variable. The following command will change the shell
prompt to HELLO>:
$ PS1=”HELLO>” <Enter>
HELLO> New prompt
While changing the shell prompt, ensure that there are no spaces before and after the = symbol. Also,
enclose the new prompt within quotation marks. The predefined prompt strings can be used to specify the
value of the PS1 variable. For example, the \w string is used to display the current working directory.
Example:
$ PS1=’\w>’
~ >cd /usr/doc
/usr/doc >_
In the above example, after you change the value of the PS1 variable, the prompt displays the tilde (~)
symbol, denoting the HOME directory. In addition, the prompt changes when you change to another
directory.
The man bash command is used to refer the man pages for the bash shell and view the prompt strings of
the PS1 variable.
The PS2 Variable
52
The PS2 variable specifies that the value for the secondary prompt. By default, the secondary
prompt is the > symbol. The Linux operating system displays the secondary prompt when you type an
incomplete command on the command line.
Example
$ PS1=’$
>
>‘
$_
In the above example, the value of the PS1 variable is enclosed within quotation marks but the quotation
marks are not closed. As a result, the command is considered incomplete. The > prompt is displayed
because of the incomplete command.
The following command is used to change the PS2 prompt:
$ PS2=^
$ echo “This is incomplete
^ close the quotes
^”
The LOGNAME Variable
The user’s login name is stored in the LOGNAME variable.
Example:
$ echo “ $ {LOGNAME} “
You might or might not enclose the LOGNAME variable in quotation marks and braces. The following
command can be used:
$ echo $LOGNAME
The SHLVL Variable
The SHLVL variable contains the shell level that is currently working in. When working on Linux,
create new shells and forget the level of the shell in which the shell is working. In the situation , the
SHLVL environment variable is used to know the level of the shell in which the shell is working. In the
Linux operating system, the login shell is assigned the number 1. When you create a new shell, the value
of the variable SHLVL is incremented by one.
Example:
$ echo $SHLVL
1 This is the login shell.
$ sh Creates a new shell.
53
$ echo $SHLVL
2 You are working in the new shell.
$ exit Terminates the child shell.
exit
$ echo $SHLVL
Returns to the parent shell, which is the login shell in this case.
Description
If env is run without any options, it prints the variables of the current environment. Otherwise, env sets
each NAME to VALUE and executes COMMAND.
env syntax
env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]
Options
-i, --ignore-environment Start with an empty environment.
-0, --null End each output line with a 0 (null) byte rather than a newline.
-u, --unset=NAME Remove variable NAME from the environment.
--help Display a help message and exit.
--version Display version information and exit.
- Same as -i.
The following example is an output of the env command
$ env
54
HOME=/computerhope/public_html
PATH=/usr/local/bin:
LOGNAME=admin
HZ=100
TERM=vt1000
TZ=MST7MDT
SHELL=/bin/csh
MAIL=/var/mail/computerhope
_INIT_UTS_PLATFORM=SUNW,SPARCstation-10
_INIT_UTS_RELEASE=5.7
_INIT_UTS_SYSNAME=SunOS
_INIT_UTS_VERSION=Generic_106541-08
EDITOR=pico -t
OPENWINHOME=/usr/openwin
MANPATH=/usr/man:/usr/local/man:/usr/openwin/man
LD_LIBRARY_PATH=/usr/local/lib:/usr/openwin/lib
PAGER=more
Command Substitution
In addition to pipes, the command substitution is used to combine more than one command in a
command line. To display the date message on the screen:
The date is (output of the date command)
To do so, enter any of the following command:
echo “The date is ‘date’”
The command date is enclosed in single backward quotation marks or a grave accent. While executing the
command, the shell first replaces the enclosed command with the output of the command. Then, the shell
executes the entire command.
The following command would also display the same output:
echo “The date is $ (date)”
The shell replaces $ (date) with the output of the date command.
The expr Command
In most shells, we cannot declare variables as integers. All variables are treated as character
strings. Therefore, in the following declaration, the variable var1 contains the characters 2 and 5, and not
the number 25:
55
var1=25
However, in Linux, can perform arithmetic operations by using the expr command to simulate numeric
variables and evaluate arithmetic expressions. The output of the expr command is sent to the standard
output file.
Example:
$ expr 4 + 5
The command in the above example will display 9 on the screen, need to add a space on either side of the
+ operator.
Example:
$ a=5
$ b=4
$ expr $a + $b
9
The operators supported by expr command are +, -, *, and /. When the * operator is used, it should
be preceded by the backslash character. If you do not precede the * operator with the backslash character,
the shell interprets the * operator as a wildcard character.
The expr command does not support decimals. The following command will display 2 and not 2.5
because the numeric value after the decimal point is ignored:
$ expr 5 / 2
The following command will result in syntax error because the decimal point in 2.5 will be treated as a
period:
$ var1 = 2.5
$ expr $var + 5
Therefore, the expr command will treat the value of the variable var1 as numeric.
The output of the expr command is displayed on the standard output file. The output of the expr
command should be stored in a variable, by using command substitution. The following command will
assign the value 25 to the var1 variable:
$ var1 = 5
$ var1 = ‘expr $var1 + 20’
The use of the expr command is shown in the following code:
a = 10
b=5
a = ‘ expr $a – 7’
echo “ a is equal to $a”
56
a = ‘ expr $a \* $b’
echo “ a is equal to $a”
a = ‘ expr $a / 3’
echo “ a is equal to $a”
The output of the code given above will be as follows:
a is equal to 3
a is equal to 15
a is equal to 5
Arithmetic Expansion
To calculate the value of an expression, enclose the expression in $ ( ( …. ) ).
Syntax
$ ( ( expression) )
Example
$ echo $ ( ( 45 + 43 ) )
79
To calculate the sum of the numbers, 45 and 34, enclose the numbers in (( )) along with the + operator.
While enclosing the expression in (( …)), can also specify variables instead of numbers in the expression.
Example
$ a = 25
$ b = 56
$ echo $ ( ( a + b ) )
81
57
UNIT - V
While writing a shell script, there may be a situation when you need to adopt one path out of the
given two paths. So you need to make use of conditional statements that allow your program to make
correct decisions and perform the right actions.
Linux Shell supports conditional statements which are used to perform different actions based on
different conditions. We will now understand two decision-making statements here −
● The if...else statement
● The case...esac statement
The if...else statements
If else statements are useful decision-making statements which can be used to select an option from a
given set of options.
Linux Shell supports following forms of if…else statement:
● if...fi statement
● if...else...fi statement
● if...elif...else...fi statement
Most of the if statements check relations using relational operators discussed in the previous chapter.
if...fi statement:
The if...fi statement is the fundamental control statement that allows Shell to make decisions and execute
statements conditionally.
Syntax if [ expression ]
then
Statement(s) to be executed if expression is true
fi
The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are
executed. If the expression is false then no statement would be executed. Most of the times, comparison
operators are used for making decisions.
58
It is recommended to be careful with the spaces between braces and expression. No space produces a
syntax error.
If expression is a shell command, then it will be assumed true if it returns 0 after execution. If it is a
Boolean expression, then it would be true if it returns true.
Example
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
The fiabove script will generate the following result −
a is not equal to b
if [ $a != $b ]
if...else...fi
then :
echo "a is not equal to b"
The if...else...fi statement is the next form of control statement that allows Shell to execute statements in a
fi
controlled way and make the right choice.
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi
The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are
executed. If the expression is false, then no statement will be executed.
Example
The above example can also be written using the if...else statement as follows −
#!/bin/sh
a=10
b=20 59
if [ $a == $b ]
then
Upon execution, you will receive the following result −
a is not equal to b
if...elif...else...fi statement :
The if...elif...fi statement is the one level advance form of control statement that allows Shell to make
correct decision out of several conditions.
Syntax
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
This code is just a series of if statements, where each if is part of the else clause of the previous statement.
Here statement(s) are executed based on the true condition, if none of the condition is true then else block
is executed.
Example
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
60
elif [ $a -lt $b ]
then
echo "a is less than b"
else
Upon execution, you will receive the following result −
a is less than b
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
61
Here the string word is compared against every pattern until a match is found. The statement(s) following
the matching pattern executes. If no matches are found, the case statement exits without performing any
action.
There is no maximum number of patterns, but the minimum is one.
When statement(s) part executes, the command ;; indicates that the program flow should jump to the end
of the entire case statement. This is similar to break in the C programming language.
Example
#!/bin/sh
FRUIT="kiwi"
case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac
#!/bin/sh
option="${1}"
case ${option} in
-f) FILE="${2}"
echo "File name is $FILE"
;;
-d) DIR="${2}"
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0}`:usage: [-f file] | [-d
directory]"
exit 1 # Command to come out of the program
with status 1
;;
esac 62
Here is a sample run of the above program −
$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d Linux
Dir name is Linux
$
LOOPS IN LINUX
In this chapter, we will discuss shell loops in Linux. A loop is a powerful programming tool that enables
you to execute a set of commands repeatedly. In this chapter, we will examine the following types of
loops available to shell programmers −
● The while loop
● The for loop
● The until loop
● The select loop
You will use different loops based on the situation. For example, the while loop executes the given
commands until the given condition remains true; the until loop executes until a given condition becomes
true.
Once you have good programming practice you will gain the expertise and thereby, start using appropriate
loop based on the situation. Here, while and for loops are available in most of the other programming
languages like C, C++ and PERL, etc.
The while loop :
The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is
usually used when you need to manipulate the value of a variable repeatedly.
Syntax
while command
do
Statement(s) to be executed if command is true 63
done
Here the Shell command is evaluated. If the resulting value is true, given statement(s) are executed. If
command is false then no statement will be executed and the program will jump to the next line after the
done statement.
Example
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces
(words). Each time the for loop executes, the value of the variable var is set to the next word in the list of
words, word1 to wordN.
Example
Here is a simple example that uses the for loop to span through the given list of numbers −
#!/bin/sh 64
for var in 0 1 2 3 4 5 6 7 8 9
do
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
until command
do
Statement(s) to be executed until command is true
done
Here the Shell command is evaluated. If the resulting value is false, given statement(s) are executed. If the
command is true then no statement will be executed and the program jumps to the next line after the done
statement.
Example
Here is a simple example that uses the until loop to display the numbers zero to nine –
#!/bin/sh
a=0
until [ ! $a -lt 10 ]
do
echo $a
a = `expr $a + 1`
done 65
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
Syntax
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces
(words). Each time the for loop executes, the value of the variable var is set to the next word in the list of
words, word1 to wordN.
For every selection, a set of commands will be executed within the loop. This loop was introduced in ksh
and has been adapted into bash. It is not available in sh.
Example
Here is a simple example to let the user select a drink of choice −
#!/bin/ksh
Nesting Loops
All the loops support nesting concept which means you can put one loop inside another similar one or
different loops. This nesting can go up to unlimited number of times based on your requirement.
Here is an example of nesting while loop. The other loops can be nested based on the programming
requirement in a similar way −
It is possible to use a while loop as part of the body of another while loop.
67
Syntax
Example
Here is a simple example of loop nesting. Let's add another countdown loop inside the loop that you used
to count to nine –
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
This will produce the following result. It is important to note how echo -n works here. Here -n option lets
echo avoid printing a new line character.0
10
210
3210
43210
543210
6543210
76543210
876543210
9876543210
68
In this chapter, we will discuss shell loop control in Linux. So far you have looked at creating loops and
working with loops to accomplish different tasks. Sometimes you need to stop a loop or skip iterations of
the loop.
In this chapter, we will learn following two statements that are used to control shell loops−
● The break statement
● The continue statement
All the loops have a limited life and they come out once the condition is false or true depending on the
loop.
A loop may continue forever if the required condition is not met. A loop that executes forever without
terminating executes for an infinite number of times. For this reason, such loops are called infinite loops.
Example
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh
a=10
until [ $a -lt 10 ]
do
echo $a
a=expr $a +forever
This loop continues 1` because a is always greater than or equal to 10 and it is never less than 10.
done
The break Statement
The break statement is used to terminate the execution of the entire loop, after completing the execution
of all of the lines of code up to the break statement. It then steps down to the code following the end of the
loop.
Syntax
The following break statement is used to come out of a loop −
The break command can also be used to exit from a nested loop using this format −
break n break
Here n specifies the nth enclosing loop to the exit from.
Example
Here is a simple example which shows that loop terminates as soon as a becomes 5 −
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
69
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
Here is a simple example of nested for loop. This script breaks out of both loops if var1 equals 2 and
var2 equals 0 −
#!/bin/sh
for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done
Upon execution, you will receive the following result. In the inner loop, you have a break command with
the argument 2. This indicates that if a condition is met you should break out of outer loop and ultimately
from the inner loop as well.
10
15
The continue statement is similar to the break command, except that it causes the current iteration of the
loop to exit, rather than the entire loop.
This statement is useful when an error has occurred but you want to try to execute the next iteration of the
loop.
Syntax
continue
Like with the break statement, an integer argument can be given to the continue command to skip
commands from nested loops.
continue n
Here n specifies the nth enclosing loop to continue from.
70
Example
The following loop makes use of the continue statement which returns from the continue statement and
starts processing the next statement −
#!/bin/sh
NUMS="1 2 3 4 5 6 7"
for NUM in $NUMS
do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done
Hello World
Example 1. Hello World
#!/bin/sh
echo "Hello world"
#!/bin/bash
Save this file as name.sh, set execute permission on that file by typing chmod a+x name.sh and then
execute the file like this: ./name.sh.
71
$ chmod a+x name.sh
$ ./name.sh Hans-Wolfgang Loidl
My first name is Hans-Wolfgang
My surname is Loidl
Total number of arguments is 2
72