0% found this document useful (0 votes)
61 views33 pages

IL-Module 3

The document provides an introduction to using the VI text editor in Linux, including descriptions of the three main modes (command, input, and last line), how to perform common editing tasks like inserting, deleting, replacing, and moving text, and how to search for strings within a file.

Uploaded by

Kanak RT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views33 pages

IL-Module 3

The document provides an introduction to using the VI text editor in Linux, including descriptions of the three main modes (command, input, and last line), how to perform common editing tasks like inserting, deleting, replacing, and moving text, and how to search for strings within a file.

Uploaded by

Kanak RT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Introduction to Linux 2020-2021

Module 3
Topics to be covered:
 VI Editor: Introduction to Text Processing, Command & edit Mode
 Invoking VI, deleting & inserting Line
 Deleting & Replacing Character
 Searching for Strings, Yanking,
 Running Shell Command Macros
 Set Window, Set Auto Indent, Set No.
 Communicating with Other Users: who, mail, wall, send, mesg, ftp.
 Shell Script: Shell types, shell command line processing.
 Shell script features
 Executing a shell script
 System and user-defined variables, expr command, shell screen interface, read and echo
statement, command substitution, escape sequence characters, Conditional Control
Structures-if statement, case statement Looping Control Structure while, until, for,
statements. Jumping Control Structures – break, continue, exit.

Introduction:
No matter what work you do with a unix system, you will eventually write some C or Java
programs for shell scripts. You may also have to edit some of the system files at a times. For
all this you must learn to use an editor, Unix provides two very versatile ones—vi and emacs.
VI is the full screen editors now available with all UNIX system, and is widely acknowledged
as one of the most powerful editors available in any environment. It was created by a
graduate student Bill Joy later to become the Co founder of Sun Microsystems. VI made its
first appearance in BSD UNIX but is now standard on all UNIX systems.

Objectives:
 Know the 3 modes of functioning.
 Input and replace text and control characters.
 Save your work recover from a crash and quit VI.
 Understand the use of operator command and combinations to delete, move and copy
text.
 Repeat and undo the last command.
 Search for a string in a file and a character in a line.

The 3 modes:
When you open a file with VI, the cursor is positioned at the top left-hand corner of the
screen. You are set to be in the command mode. This is the mode where you pass commands
to act on text. Pressing a key does not show it on screen but make a function like moving the
cursor to the next line or deleting a line. You can’t use the command to enter or replace text.

Jain School of CS and IT


Introduction to Linux 2020-2021

There are two command mode functions that you should know at this stage. The role of the
space bar and the backspace key. This spacebar takes you one character ahead, while back
space or control h takes you a character back. Backspacing in this mode does not delete text
at all.
To enter text, you have to leave the command mode and enter the input mode. There are 10
keys which take you to this mode when pressed, and whatever you then enter shows up on
screen. Backspace in in this mode, erase all characters that the cursor passes through. To
leave this mode you can press escape key.
You have to save your work, leave VI editor or switch to editing another file. Sometimes Will
need to make a global substitution in the file. Neither of the two modes will quite do the work
for you. You have to use the last line mode or EX mode, where you enter the instruction in
the last line of the screen. Some common mode function also has last line mode equivalents
with this we can summarise that 3 modes in which vi works:

 Commander mode – where keys are used as commands to act on text.


 Input mood – where any key depressed is entered as text.
 Last line mode or ex mode: where commands can be entered in the last line of the
screen to act on text.
The relationship between these 3 modes and the shell is depicted in the following
figure.

The .exrc file:


The behaviour of VI is controlled by a configuration file – the one it reads on start-up.
Many unix commands have their own configuration files, and the one used by vi is
.exrc . You may find this file in your home directory – the directory where you are
placed upon logging in. many of the commands used in the last line mode can also be
placed in this file.
The .exrc file is not displayed by the LS command unless it is used with a special
option -a. if it still does not show up you can create your own, or ask the System
Administrator to give you a default file.

vi commands are case sensitive. The command a is not same as A.

 The vi editor opens in this mode, and it only understands commands


 In this mode, you can, move the cursor and cut, copy, paste the text
 This mode also saves the changes you have made to the file
 Commands are case sensitive. You should use the right letter case.

How to use vi editor


To launch the VI Editor -Open the Terminal (CLI) and type
vi <filename_NEW> or <filename_EXISTING>

Jain School of CS and IT


Introduction to Linux 2020-2021

And if you specify an existing file, then the editor would open it for you to edit. Else,
you can create a new file.

Jain School of CS and IT


Introduction to Linux 2020-2021

Jain School of CS and IT


Introduction to Linux 2020-2021

Editing require that you be in command mode. Many of the editing commands have a
different function depending on whether they are typed as upper- or lowercase.

 Moving the Cursor

To move the cursor to another position, you must be in command mode. The cursor is
controlled with four keys: h, j, k, l.
h left one space
j down one line
k up one line
l right one space

 Inserting Text

To insert text in a line:

1. Position the cursor where the new text should go.

2. Type i

3. Enter the new text.

The text is inserted BEFORE the cursor.

4. Press <Esc> to get back to command mode.

Jain School of CS and IT


Introduction to Linux 2020-2021

 Replacing Words

To replace / change one word with another,

1. Move to the start of the incorrect word

2. Type cw

The last letter of the word to be replaced will turn into a $. You are now in insert
mode and may type the replacement. The new text does not need to be the same
length as the original.

3. Press <Esc> to get back to command mode.

To replace /change three words, type 3cw


To change the entire line, type cc

 Replacing Lines

To change text from the cursor position to the end of the line:
1. Type C (uppercase).
2. Type the replacement text.
3. Press <Esc>.

 Deleting Characters

To delete a character from a file, move the cursor until it is on the incorrect character,
then type x

 The character under the cursor disappears.

To remove four characters starting from the cursor position type 4x.
To delete the character before the cursor, type X (uppercase)

 Deleting Words

To delete a word, move the cursor to the first letter of the word, and type dw

 This command deletes the word and the space following it. To delete three words type
3dw

 Deleting Lines

To delete a whole line, type dd

Jain School of CS and IT


Introduction to Linux 2020-2021

 The cursor does not have to be at the beginning of the line. Typing dd deletes the
entire line containing the cursor and places the cursor at the start of the next line.

To delete two lines, type 2dd


To delete from the cursor position to the end of the line, type D (uppercase).

 Text Movement (you can delete text from one place and put it at another place, i.e.
cut and paste)

To move a line from one place to another:


1. Put the cursor on the line to be deleted.
2. Type dd
3. Move the cursor to the position where you want to put the line
4. Type p or P
5. Small p will put the line below the cursor position while capital P will put the
above the cursor position. You can repeat the put command by moving cursor
to different places and paste the text.
6. To move several lines associate a number with dd, example: 3dd for 3 lines.
To move one or more words, delete the words using dw, then put the deleted words to
the right of the cursor position using p or use P to put the words to the left of the
cursor position.

 Yanking (you can copy text from one place and put it at another place, i.e. copy and
paste)

To copy a line from one place to another:


1. Put the cursor on the line to be copied.
2. Type yy
3. Move the cursor to the new position
4. Type p or P
5. Small p will put the line below the cursor position while capital P will put the
above the cursor position. You can repeat the put command by moving cursor
to different places and paste the text.
6. To copy several lines associate a number with yy, example: 2yy for 2 lines
To copy one or more words, copy the words using yw, then put the copied words to
the right of the cursor position using p or use P to put the words to the left of the
cursor position.

 Searching String

To move quickly by searching for text, while in command mode:


1. Type / (slash).
2. Enter the text to search for.

Jain School of CS and IT


Introduction to Linux 2020-2021

3. Press <Return>.
The cursor moves to the first occurrence of that text.
To repeat the search in a forward direction, type n
To repeat the search in a backward direction, type N

 Joining Lines

To join two lines together:


1. Put the cursor on the first line to be joined.
2. Type J
To join three lines together:
1. Put the cursor on the first line to be joined.
2. Type 3J

 Undoing
 To undo your most recent editing, type u
 To undo all the edits on a single line, type U (uppercase)
 Undoing all edits on a single line only works as long as the cursor stays on that
line. Once you move the cursor off a line, you cannot use U to restore the line.
 Repeating
 To repeat the most recent editing, type . (dot).

With vi, you edit a copy of the file in the Buffer, rather than the original file. Changes
are made to the original only when you save your edits.

 To save the file and quit vi, type ZZ . It doesn’t have any other command to do that.

However, the vi editor is built on an earlier Unix text editor called ex. ex commands
can be used within vi. ex commands begin with a : (colon) and end with a <Return>.
The command is displayed on the status line as you type. Some ex commands are
useful when saving and closing files.

 To save the editing you have made, but leave vi running and your file open:
1. Press <Esc> to come to the Command Mode.
2. Type :w
3. Press <Return>.
 To save the editing you have made, and quit vi use :wq or :x
 To quit vi, and discard any changes your have made since last saving:
1. Press <Esc>.
2. Type :q!
3. Press <Return>.

If no changes have been made then use :q

Jain School of CS and IT


Introduction to Linux 2020-2021

Summary:
 Command mode cursor-motion commands:
o j down
o k up
o l right
o h left
o $ move to end of current line
o ^ move to beginning of current line
o G go to bottom line
o nG go to line number n
 Command mode screen-motion commands:
o ctr-d down
o ctr-u up
 Command mode enter-insert-mode commands (once you are in insert mode you stay
there until you press esc):
o I insert here (before cursor)
o a insert here (after cursor)
o o insert a new line (below current line)
o O insert a new line(above current line)
 Insert-mode commands:
o esc return to command mode
o ctr-u erase back line
o ctr-w erase back word
o ctr-h erase back character
 Delete commands (from command mode):
o x delete character at cursor
o dd delete entire line
o D delete current to end of line
 Copying lines:
o #yy yanks # lines, puts in buffer
o p inserts buffer after current line
 Moving lines:
o #dd delete # lines (now in buffer)
o p inserts buffer after current line
 Special commands:
o . repeat last command
o u undo last command
o J join next line to end of current line
o :set nu set line numbers on
o :set nonu set line numbers off

Jain School of CS and IT


Introduction to Linux 2020-2021

 Search and replace commands:


o /string searches forward for string
o / or n repeat search
o ?string searches backward for string
o ? or n repeat search
o :/string/s//replace replaces string with replace on this line
o :g/string/s//replace/g replaces string with replace on every line, every
occurrence on the line
o :%s/old/new/g replace old with new on all lines
 Exiting
o :wq quit, writing file first
o :q! quit, don't write first
o :w file_name write this file to a new file
o :w! file_name write to an existing file

Running shell commands from vi


 You can run UNIX commands and see their output without leaving vi. You can also
insert the output of a UNIX command into the file that you are editing.
To run a single UNIX command in vi:
1. Press <ESC> to come to command mode
2. Type :!UNIX_command
3. Press <Enter>
To insert the output from a UNIX command into a file, immediately after the cursor:
This facility would be very useful if you were using vi to document a UNIX
command and you wanted to include examples of the output from this command.
1. Press <ESC> to come to command mode
2. Type :r!UNIX_command
3. Press <Enter>
 You can start a shell from within vi and use it like your usual terminal environment,
then return to using vi by entering the command exit
To start up a shell:
1. Press <ESC> to come to the command mode
2. Type :sh
3. Press <Enter>

Customizing vi using set commands

Jain School of CS and IT


Introduction to Linux 2020-2021

 Several set commands are available which are suitable for writing programs and
preparing documents in vi editor. These commands work in ex mode.
Syntax: :set option
When the command option is prefixed with string no, it reverses the command.
 Autoindent option provides indents to lines for easier readability. Commands are:
:set autoindent and :set noautoindent
 Number option shows lines duly numbered that helps to debug programs. However,
the line numbers are not saved to the file. Commands are:
:set number and :set nonumber
 Ignorecase option allows to ignore case while searching patterns in the file.
:set ignorecase and :set noignorecase
 Showmode option displays a message when vi is in input mode
:set showmode and :set noshowmode
 Tabstop sets tab for display (default tab space is eight characters), for example:
:set tabstop=12
Options to vi:
Vi has couple of options to be used while opening file.
 The option -r is used to salvage/recover unsaved editing when crash occurred.
However, it does not guarantee complete retrieval.
Syntax: $ vi -r <filename>
 The + option with a line number opens the file and positions the cursor at the first
word of that line number. For example: to start at line number 10
Syntax: $ vi +10 <filename>
 The +/ option with a string as pattern opens the file and positions the cursor at the
line that matches the pattern.
Syntax: $ vi +/string <filename>

Programming with the Shell


Basics:
 Shell is the command interpreter; it interprets user commands and interacts with the
Kernel to perform the tasks on behalf of the user in the Unix/Linux environment.

Jain School of CS and IT


Introduction to Linux 2020-2021

 It also offers programming capability using which a user can control how and when
commands are to be executed.
 Programs written in shell command language are called shell scripts. At its simplest
form a shell script is just a sequence of commands that have been saved in a file.

Why Shell Scripts?


The shell is a high-level programming language and easier to learn than other
languages such as C or C++.
Shell scripts are generally faster to write and often easier to debug than
corresponding C programs.
Shell scripts are interpreted rather than compiled; No need to convert it to binary
executables.
If you are writing a program that relies heavily on UNIX commands, shell script is an
excellent choice.
For quickly writing relatively short programs, shell script is a much better choice, but
for large and complex systems programming tasks, C is clearly superior.

Some use cases for Shell Script


How to use
Combine lengthy and repetitive sequences of commands into a single, simple
command using shell script to work with file system.
Generalize a sequence of operations on one set of data, into a script that can be
applied to any similar set of data in text processing.
Create new commands using combinations of utilities in ways the original authors
never thought of.
When to use
System boot scripts to customize Unix/Linux environment
System administrators, for automating many aspects of computer maintenance, user
account creation, backup procedure etc.
Application package installation tools for initialization setup
Application startup scripts, to perform some repeated configuration tasks.
TYPES OF SHELLS:
The original UNIX System shell, sh, was written by Steve Bourne in 1978, and it is
known after his name. Because it was the first, the Bourne shell lacks many

Jain School of CS and IT


Introduction to Linux 2020-2021

enhancements common to the later shells. It can still be useful for certain tasks such
as scripting, but almost all users will prefer one of the newer shells for entering
commands. ( part of AT&T version of Unix)
The C shell, csh, was the first attempt to enhance the original Bourne shell. The
syntax was strongly influenced by the C programming language. The C shell
introduced the concepts of a command history list, job control, and aliases. However,
like sh, it lacks some important features of later shells. A common complaint about
csh is that the new syntax is not compatible with the Bourne shell, and so some scripts
may not work properly in csh. ( part of BSD version of Unix)
The extended C shell, tcsh, has replaced csh entirely on some versions of UNIX
(including Linux). It retains all the features of csh and adds command-line editing (a
very important shell feature) and history completion. It is one of the more popular
shells, although like csh it has been criticized for not being compatible with the
Bourne shell.
The Korn shell, ksh, was developed at AT&T Bell Laboratories by David Korn.
Unlike the C shell, the Korn shell has a syntax compatible with sh. Like tcsh, ksh
includes a command history list, job control, aliases, and command-line editing.
The Bourne Again Shell, bash, is part of the GNU project. It extends ksh further,
while remaining compatible with the original Bourne shell syntax, and adds a few
features from tcsh as well. bash is the default shell in Linux and may be the most
popular shell today. On some systems, the command sh will run bash instead.

Comparison:
sh-Bourne Shell; csh-C Shell; ksh-Korn Shell; tcsh-Extended C Shell; bash-Bourne
Again Shell.

Your First Encounter with a Script:


Creating a Script File

Jain School of CS and IT


Introduction to Linux 2020-2021

Using any text editor of your choice such as vi or gedit, create a new file hello.sh
with the following:
#!/bin/bash
# This is my First Script
echo "Hello World"
ls
date

Executing a Script File


Use any of the following ways to execute the script file hello.sh ( invoking shell type
or using dot command)
$ bash hello.sh
$ sh hello.sh
$ . hello.sh
Use chmod command to make the script file hello.sh executable
$ chmod +x hello.sh
Now you can execute the file like a command by typing the name of the executable
file and prefixing it with a dot and slash combination if the script is in your current
directory. Here dot refers to current directory and slash is pathname separator. If it
is in a different directory, then use appropriate pathname with the executable script
file name.
$ ./hello.sh

Understanding the first script:


The #!/bin/bash line is called the shebang line. The #! Character sequence is, in fact, a
special construct called a shebang. The shebang is used to tell the system the name of
the interpreter that should be used to execute the script that follows. This should
always be the first line in a Shell script.
If the shell that executes your script is available by prior configurations then the
shebang line can be omitted.
The next few lines in the shell script are self explanatory:

Jain School of CS and IT


Introduction to Linux 2020-2021

Any line starting with #, will be treated as a comment line. An exception to this would be the
first line with #!/bin/bash
The echo command will print HelloWorld on the screen
The ls command will display directory content on the console
The date command will show the current date and time
File name extension .sh is not mandatory

Configuring vi For Script Writing:


 Install the advanced version of vi to support syntax highlighting
$ sudo apt install vim
 When your script file is open in vi/vim editor use the following configuration settings
for ease script development:
 Turn on syntax highlighting.
:syntax on
 Turn on the option to highlight search results.
:set hlsearch
 Turn on the “auto indent” feature.
:set autoindent
 Turn on line numbering.
:set number
 sets the number of columns occupied by a tab character.
:set tabstop=4

Variables:
In Linux, there are two types of variable: system, and user-defined.
System variables - Created and maintained by Linux itself. This type of variables are
defined in CAPITAL LETTERS.
System variables are used in .profile file to alter operating environment of a user and
are also called environment variables.
To know the complete list give the following command:
$ set
To print a variable’s value, for example:

Jain School of CS and IT


Introduction to Linux 2020-2021

$ echo $HOME

A small list of environment/ system variables

 User defined variables (UDV) - Created and maintained by user. This type of
variables are defined in lower case letters preferably. To define UDV use following
syntax

Jain School of CS and IT


Introduction to Linux 2020-2021

 Syntax: variable_name=value
 No spaces are permitted around the equal sign. Adding spaces will change the syntax
profoundly and generate error.
 Bash variable are Untyped, basically character strings, but can be numeric also.
 To print or access UDV use following syntax
 Syntax: $variable_name
 Examples:
 x=10
 echo $x
 message="Hello World"
 echo $message
 Rules for Naming Variables
 A variable name can contain only letters (a to z or A to Z), numbers ( 0 to 9)
or the underscore character ( _). Variables are case-sensitive.
 Do not use ?,* and other special characters, to name your variable.
 Double Quotes: Enclosing characters in double quotes (“ ”) are basically literals, with
the exception of ‘$’, ‘`’ ‘\’. These characters retain their special meaning within
double quotes.
 Single Quotes: Enclosing characters in single quotes (‘ ’) are absolutely interpreted as
literal with no exception for special meaning of any character.
 Back Quote: ‘`’ is used to execute a command
 Back slash: ‘\’ is used to change the special meaning of the characters or to escape
special characters within the double quotation marks.
 Examples:
 echo “Your shell is: $SHELL”
 echo ‘Your shell is: $SHELL’
 echo “Today is `date`”
 echo “Your shell is: \$SHELL”
Output with echo:
 Display text or values of variables on the standard output using echo.
Syntax: echo [options] [string, variables...]

Jain School of CS and IT


Introduction to Linux 2020-2021

Options:
 -n Do not output the newline character at the end
 -e Enable back slash escape characters in the strings:
 \n new line
 \t horizontal tab
 \v vertical tab
 \\ backslash
 \a alert (bell)
 \b backspace

 Examples:
 echo -n “What is your name? ”
 echo “My name is Jain”
 echo -e “What is your name?\nMy name is Jain”
 echo $PWD

Input with read:


 Get data input from the standard input using read and capture using variables.
Syntax: read [options] [variables...]
Options:
 -p Prompt a string without a newline before read
 -s Make the input secret; do not display input on the terminal
 Examples:
 read x
 read x y
 read -p “What is your name? ” name
 read -s -p “Enter password: ” pass
 Example:
 echo -n “What is your name? ”
 read name

Jain School of CS and IT


Introduction to Linux 2020-2021

 echo $name
Example script:
1. #!/bin/bash
2. # A Script to create a 3 level nested directory
3. read -p “Enter 3 directory names to create: ” d1 d2 d3
4. mkdir -p $d1/$d2/$d3
5. echo -e “\nHere goes the structure:”
6. ls -R $d1

Command Substitution:
 Command substitution allows the output of a command to replace the command itself.
Command substitution occurs when a command is enclosed as follows:
 $(command) OR `command`
 Command substitution is generally used to assign the output of a command to a
variable or display back using echo command:
 var-name=$(command-name)
 var-name=`command-name`
 echo “$(command-name)”
 echo “`command-name`”
 Examples:
 $ x=`date`
 $ x=$(date)
 $ echo “Today is $(date)”
 $ echo “Today is `date`”
Command-line Arguments or Positional Parameters:
Command-line arguments are used to input data to a script. When you execute a
script, pre-defined shell variables are automatically set to match the arguments. These
variables are referred to as positional parameters.
The parameters $1, $2, $3, $4 (up to $9) refer to the first, second, third, fourth (and so
on) arguments on the command line. The parameter $0 is the name of the shell

Jain School of CS and IT


Introduction to Linux 2020-2021

program itself. The parameter $# is the total number of arguments passed to the script.
The parameter $* refers to all of the command-line arguments (does not include the
name of the script).

Example Script:
1. #!/bin/bash
2. #Script to test command-line arguments
3. echo “Script Name: $0”
4. echo “Total No of Arguments: $#”
5. echo “First Argument: $1”
6. echo “All Arguments Passed: $*”

How to run:
1. Create a script file and save this script.
2. Assign execute permission to the script file.
3. Run the script with some arguments.
Exit status:
In Linux, when a command is executed, it return two type of values: a zero (0) if the
command is executed successfully, or a nonzero (>0) if the command is not
successful.
This value is know as Exit Status of that command and is stored in a predefined
variable $?.
You can check this value to determine next course of action in the script.
 For example:
 In the previous script, you can check the exit status and if the command executes
successfully then you display the directory structure.
Arithmetic Operations
 Using expr: The command takes a list of arguments, evaluates them, and prints the
result on standard output. Each term must be separated by spaces. The basic operators
+, −, *, /, and % can be used with expr.
 For example: $ expr 1 + 2
 You can use command substitution to assign the output from expr to a variable.
 For example, you could increment the value of i with : $ i=1; i=`expr $i + 1`

Jain School of CS and IT


Introduction to Linux 2020-2021

 Drawbacks of expr
The * must be escaped with a backslash to prevent the shell from interpreting it as an
asterisk (wild-card):
 $ expr 4 \* 4
It can only be used for integer arithmetic. If you use a decimal argument, you get an
error, and it will truncate decimal results.
 For example: $ expr 1.5 + 2.5 will result error and $ expr 7 / 2 will result 3

 Using let: The let command is a better alternative to expr and provides integer
arithmetic. It accommodates several operators including +, -, *, /, %, and **. Here is a
simple use of let:
 $ x=100
 $ let y=2*(x+5)
 $ echo $y
Note: the let automatically uses the value of a variable like x, no need to add a $ in
front of the variable name. But no decimal argument can be used. No space between
operands. No need of escape character for *

 Using declare: We can declare a variable as an integer by using the declare command
and then assign the value of an arithmetic expression. No white space between terms
in the expression permitted.
$ declare –i var
$ var=(5+6)*3+(9-1)/2
$ echo $var
 Using arithmetic expansion: We can use two different ways for evaluating
arithmetic expressions:
 Syntax: $((expression))
 Syntax: $[expression]
 Examples:
$ echo $[(3+4)*5+9]
$ var=$[(3+4)*5+9]
$ echo $((5**3)

Jain School of CS and IT


Introduction to Linux 2020-2021

 Floating-point arithmetic: Floating point arithmetic can be performed using other


utilities such as bc:
 Example:
$ echo “scale=2; 5/3” | bc

Example Script:
1. #!/bin/bash
2. echo "Enter first value"
3. read var1
4. echo “Enter second value”
5. read var2
6. echo `expr $var1 + $var2` # Arithmetic Addition
7. echo `expr $var1 - $var2` # Arithmetic Subtraction
8. echo `expr $var1 \* $var2` # Arithmetic Multiplication
9. echo `expr $var1 / $var2` # Arithmetic Division
10. echo `expr $var1 % $var2` # Arithmetic Modular Division
11. let p=var1**var2 # Use of let
12. echo “Power computation: $p”
13. sum=$(($var1+$var2)) # Use of Arithmetic Expansion
14. echo “Sum is $sum”
15. echo “Sum is $[$var1+$var2]” # Use of Arithmetic Expansion.

Operators:
 Numeric Comparison Operators: Relational Operators that are specific to
numeric values and used for integer tests

Operator Description

arg1 -eq
True if arg1 equals arg2
arg2

Jain School of CS and IT


Introduction to Linux 2020-2021

arg1 -ne
True if arg1 is not equal to arg2
arg2

arg1 -lt
True if arg1 is less than arg2
arg2

arg1 -le
True if arg1 is less than or equal to arg2
arg2

arg1 -gt
True if arg1 is greater than arg2
arg2

arg1 -ge
True if arg1 is greater than or equal to arg2
arg2

String Comparison Operators: Relational Operators used for String Tests

Operator Description

-z string True if the length of string is zero

-n string True if the length of string is non-zero

string1 = string2 True if the strings are equal

string1 != string2 True if the strings are not equal

string1 < string2 True if string1 sorts before string2 lexicographically

string1 > string2 True if string1 sorts after string2 lexicographically

File Operators: use to test files; Over 20 file operators are available in Bash Shell;
Important operators are listed.

Operator Description

-d filename True if the file exists and is a directory

Jain School of CS and IT


Introduction to Linux 2020-2021

-e filename True if the file exists; it can be empty or have some content

-f filename True if the file exists and is a regular file

-h filename True if the file exists and is a symbolic link

-r filename True if the file exists and is readable

-s filename True if the file exists and has a size greater than zero

-w filename True if the file exists and is writable

-x filename True if the file exists and is executable

Logical Operators:

Operator Description

! This is logical NOT

-o This is logical OR

-a This is logical AND

If / If-else Command:
 An if command tests whether a given condition is true. If it is, the commands within
the then block will be executed, otherwise the else block is executed. The condition
can be a logical expression or a shell command.
if command
then
command(s)

Jain School of CS and IT


Introduction to Linux 2020-2021

fi
 Example Script:
# !/bin/bash
# Pass two directory names as command-line arguments.
if cp -r $1 $2
then
rm -rf $1
echo “Backup success!”
fi

If-elif-else Command: Example Script:


Syntax: 1. #!/bin/bash
2. echo “File Name: $1 "
if expression_1
3. if ! [ -e $1 ]
then 4. then
5. echo "..Does not exist"
command(s) 6. exit 0
7. elif [ -x $1 ]
elif expression_2 8. then
then 9. echo “ File exists and Executable"
10. else
command(s) 11. echo “ File exists and not Executable"
12. fi
elif expression_3
then
command(s)
else
command(s)
fi

How to run:
1. Create a script file.
2. Make it executable and run.
If the file passed as argument does not exist, the script execution stops and it exits to
theSchool
Jain shell. of CS and IT
Introduction to Linux 2020-2021

Case command:
If you need to compare a variable against several possible values, you can use a long
chain of if ... elif ... else statements. However, the case command provides a cleaner,
more readable alternate syntax for a multi-level if-else-fi commands. It also allows
you to compare a variable to a shell wildcard pattern, rather than to a specific value.
Syntax:
case $variable-name in
pattern1)
command(s) ;;
pattern2)
command(s) ;;
.
.
patternn)
command(s) ;;
*)
command(s) ;;
esac
1. The $variable-name is compared against the patterns until a match is found. The shell
then executes all the statements up to the double semicolons (;;) at which point the
case statement terminates.
2. If the value of $variable-name does not match any of the patterns, the program goes
through the entire case statement.
3. The default is *) and it is executed if no match is found.
Example Script:
#!/bin/bash
month=$(date +%m)
case $month in

Jain School of CS and IT


Introduction to Linux 2020-2021

02)
echo "February usually has 28 days."
;;
04|06|09|11)
echo "The current month has 30 days."
;;
*)
echo "The current month has 31 days."
;;
Esac

Looping Control Structures in Shell Script:


A loop allows you to repeatedly execute a block of commands before proceeding
further in the script.
The shell has four different loop structures: for, while, until, and select.
Each of these has its own purpose and strengths & weaknesses
The two main types of loop frequently used are for and while.
The until loop is a variation on while loop.
The looping structures can be nested one within another.

For loop:
1. The for loop takes a list of items to iterate through until it reaches the end.
2. The list of items has to be written out explicitly in the script itself .
3. Also, it can iterate through the content of a variable, pattern or even through the
output of other commands execution.
4. If you omit the in list portion of the for loop, the value of $* will be used instead. You
could use this to iterate through the command-line arguments to a script.

The for loop executes a block of commands once for each member of a list. The
syntax is:

Jain School of CS and IT


Introduction to Linux 2020-2021

Syntax:
for i in list
do
command(s)
done
Example 1:
#The script runs touch command to create empty files
for x in 1 2 3 4 5 6 7 8 9
do
touch file$x.txt
done

While loop:
The while loop keeps on executing the commands in the body of the loop while the
condition that it tests for remains true. The condition is usually a logical test. The
syntax of the while loop is:
Syntax:
while condition
do
command(s)
done
Example 1:
1. #!/bin/bash
2. #Simple counting using while loop
3. i=1
4. while [ $i -le 10 ]
5. do
6. echo $i
7. i=`expr $i + 1`
8. done

Jain School of CS and IT


Introduction to Linux 2020-2021

until loop:
The until loop is exactly like the while loop but the test is negated. The syntax of the until
loop is:
Syntax:
until condition
do
command(s)
done

break and continue commands:


 Normally, execution of a loop continues until the logical condition of the loop is met.
Sometimes, however, you want to exit a loop early or skip certain commands.
The bash shell provides two built-in commands that can be used to control program
flow inside loops.
 The break command immediately terminates a loop, and program control resumes
execution with the next statement following the loop.
The continue command causes the remainder to the loop to be skipped, and program
control resumes with the next iteration of the loop.
 In a set of nested loops, break exits the immediately enclosing loop. If you give break
a numeric argument, the program breaks out of that number of loops, so for example,
break 3 would exit a set of three nested loops all at once.
continue sends control back to the top of the smallest enclosing loop. If a numeric
argument is given, control goes to the top of the nth enclosing loop.

Example 1:
1. #!/bin/bash
2. #Infinite loop terminates when user enters zero
3. while true
4. do

Jain School of CS and IT


Introduction to Linux 2020-2021

5. echo -n "Enter any number (0 to exit): "


6. read num
7. if [ $num -eq 0 ]
8. then
9. break
10. else
11. echo "Square of $num is $[ num * num ]."
12. fi
13. done
14. echo “End of Script”
Example 2:
1. #!/bin/bash
2. #Script prints only regular files present in current working directory skipping
directory files
3. for file in *
4. do
5. if [ -d $file ]
6. then
7. continue
8. fi
9. echo $file
10. done

Example 3:
1. #!/bin/bash
2. #Script prints only executable script files and skips others
3. for file in *.sh
4. do
5. if ! [ -x $file ]

Jain School of CS and IT


Introduction to Linux 2020-2021

6. then
7. continue
8. fi
9. echo $file
10. done
select Loop:
 The select command is a very useful tool for menus design. It originally comes from
the Korn shell, but is also found in bash.
 It displays a numbered list of items, displays a prompt, and waits for input. Once the
selection is processed, the user is prompted for input again. It continuously loops
around until the loop ends.
 One interesting aspect of the select loop is that it has no conditional test at all; the
only way to end the loop is to use break or exit command.
 The variable PS3 is used to set the prompt for input. It also sets $REPLY to the menu
option entered by the user. If an invalid option is typed in by the user, the variable is
not set.
 If the user presses ENTER without making a selection, the list of items is displayed
again.
 A case statement is used in the script to execute the chosen menu option.
Syntax:
PS3=“prompting-text”
select var in item1 item2 item3
do
commands
done
Example Script:
1. #!/bin/bash
2. #Simple menu using select loop
3. PS3=“Enter your choice: ”
4. echo “MENU”
5. select item in “File Copy” “File Move” “Quit Menu”
6. do

Jain School of CS and IT


Introduction to Linux 2020-2021

7. case $REPLY in
8. 1)
9. read -p “Enter source file: ” source
10. read -p “Enter destination: ” destination
11. if cp $source $destination
12. then
13. echo “File successfully copied …”
14. else
15. echo “Copy failed!”
16. fi
17. ;;
18. 2)
19. read -p “Enter source file: ” source
20. read -p “Enter destination: ” destination
21. if mv $source $destination
22. then
23. echo “File successfully moved …”
24. else
25. echo “Move failed!”
26. fi
27. ;;
28. 3)
29. echo “Thanks for using the script!”
30. break
31. ;;
32. *)
33. echo “Invalid choice!”
34. ;;
35. esac

Jain School of CS and IT


Introduction to Linux 2020-2021

36. done

Jain School of CS and IT

You might also like