Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

Students frequently turn to Computer Class 11 GSEB Solutions and GSEB Computer Textbook Solutions Class 11 Chapter 7 Vim Editor and Basic Scripting for practice and self-assessment.

GSEB Computer Textbook Solutions Class 11 Chapter 7 Vim Editor and Basic Scripting

Question 1.
Explain different modes available in Vim editor.
Answer:
Vim Modes
The Vim editor functions in three different modes, they are
(1) The command mode
(2) The insert mode
(3) The last line mode

(1) The Command Mode :

  • When we first start editing a file using the Vim editor, the editor will be opened in a command mode.
  • Thus by default the editor will start in the command mode.
  • Note that when using command mode we can’t insert text immediately. We first need to issue an insert (i),append (a) or open (o) command to insert the text in the file.
  • An extension in the command mode is a visual mode.
  • Visual mode is a flexible and easy way to select a piece of text from the file.
  • Visual mode is the only way to select a block of text that needs to be modified.
  • Following table shows the characters that assist us in the visual mode.
Command Usage
v Switch to the visual mode (allows us to manipulate characters)
V Switch to the visual mode (allows us to manipulate lines)
CTRL + v Switch to the block-visual mode (allows us to manipulate rectangular blocks of text)

Characters that are used in visual mode

(2) The Insert Mode :

  • When an insert, append, or open command is issued, we will be in insert mode.
  • Once in an insert mode we can type text into our file or navigate within the file.
  • We can toggle between the command mode and the insert mode by pressing the ESC key.
  • Following table shows the characters that assist in the insert mode.
Command Usage
a To insert text after the current cursor position.
i To insert text before the current cursor position.
A To append text at the end of the current line.
I To insert text from the beginning of a line.
O To insert in a new line above the current cursor position.
0 To insert in a new line below the current cursor position.

Characters that are used in the insert mode

(3) The Last Line Mode :

  • The last line mode normally is used to perform operations like quitting the Vim session or saving a file.
  • To go to the last line mode we first need to be in the command mode
  • From command mode we can go to the last line mode by pressing the colon(:) key.
  • After pressing the colon(:) key, a colon character is seen at the beginning of the last line of Vim editor window with cursor blinking near it. This indicates that the editor is ready for accepting a “last line command”.
  • We can toggle back to the command mode from the last line mode by pressing the ESC key twice or by pressing the [Backspace]key until the initial character is gone along with all the characters that we had typed or by simply pressing the ENTER key.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

Question 2.
List and explain the working of different save options of Vim editor.
Answer:
Saving the File

  • After we finish writing the contents we need to save this file.
  • To save the file we need to switch to the last line mode from the insert mode.
  • Press the ESC key and type colon(:).
  • Note that colon is displayed in the bottom of the screen.
  • Type wq(write and quit)as shown in figure and press the Enter key.
  • The Vim editor will now be able to see the shell prompt.
  • To see the contents of the file we can use the cat command.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 1

  • There are several other commands available to save a file depending on the current status and usage. 4
  • Following table shows commands that can be used in the last line mode along with their usage.
Command Usage
:w To save file and remain in editing mode
:wq To save file and quit editing mode
X To save file and quit editing mode (same as above)
:q To quit editing mode when no changes are made
:q! To quit editing mode without saving changes made in the file
:saveas FILENAME To save existing file with new name and continue editing it under the new file name.

The last line mode commands to save the file

  • If we open the Vim editor without typing file name initially the text will be directly stored in the system buffer (main memory).
  • To transfer the contents from the buffer to a hard disk (save a file )we need to type the file name along with the wq command.

Question 3.
Explain the different between using dd and 2dd command.
Answer:
dd command in Linux shell script deletes one line and 2dd deletes two lines.

Question 4.
What is a shell script ?
Answer:
Shell Script

  • Methods that allow us to execute commands one at a time are :
    1. Command executed from command prompt
    2. Command executed using ! in Vim Editor.
  • A shell script allows us to execute more than one command at one go in a better way.
  • Thus instead of spending time in typing the commands on the prompt every time a task needs to be performed, we can created a shell script and execute the given set of commands by typing a single line command.
  • Shell script can be defined as “Set of commands written in plain text file that performs a designated task in a controlled order.”
  • Shell script can be designed to be interactive;such a script may accept input from the user and perform different tasks based on the input provided.
  • Creating and Executing a Shell Script :
    1. We can create the shell script using any text editor.
    2. Using Vim editor let us create a shell script that welcomes a user.
    3. Type the script shown in the box below in Vim editor and save it with the name scriptl.sh.
#Script 1: Script to welcome the user who has logged into the system
clear
echo Hello
who am i
echo Welcome to Ubuntu Linux
  • The extension “sh” is basically used to specify that the file is a shell script.
  • Note that it is not mandatory to create a file with an extension “sh”, a file without extension can also be used as a shell script. But is always a good practice to give extension as it will help us to differentiate between normal files and shell script files.
    1. First line begins with symbol Any line preceded by the # symbol is considered as a comment. The comments when part of the script are not executed; they are messages that help user understand the usage or meaning of the script.
    2. The second line has clear command which clears the screen contents before giving the output of the script.
    3. The third line displays a message “Hello”.
    4. The fouth line executes a command “who am i ” that gives the name and some additional details of the user currently logged into the system.
    5. The last line displays a message “Welcome to Ubuntu Linux”.
  • To execute the script use sh or bash command.
  • If the script is stored in current directory then type the command mentioned below :
    $bash scriptl.sh or $sh scriptl.sh

    • For a script to be executed it needs to have execute permission explicitly set.
    • When we come across issues related to file privileges, we will use chmod command to set the desired privileges.
    • For example issue the following command to make file executable.
      $chmod +x script1.sh
  • Again execute scriptl.sh using bash or sh command and now if everything goes fine we will get the output similar to the one shown in Figure.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 2

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

  • Observe that in above figure we are getting some additional contents along with the user name.
  • Let us remove the additional contents using knowledge of filters.
  • Type the modified script in Vim editor as shown below and save it as script2.sh :

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 3

  • Compared to script 1 .there is change in third line in script 2.
    1. We have used the filter cut along with the command who am i.
    2. Both commands are joined using pipe symbol.
    3. To make sure that the contents within the double quotes after the echo command are not treated as message we enclose them in back quotes ( ‘ ‘ ).
    4. The back quotes are printed on the key with ~ sign on the keyboard.
  • Execute the script and you will observe that we are only able to see only the name of the user.
  • Following figure shows the output of the modified script.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 4

  • Let us further modify script2 to display current date and time also.
  • Type the following script in Vim editor and name it as script3.sh

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 5

Question 5.
List at least three uses of shell script.
Answer:
Use of Shell Scripts

  • The shell script is a very powerful tool of Linux.
  • It has almost all the capabilities of any higher level programming language.
  • Generally the repetitive task should be done using the shell scripts.
  • Some uses of Shell Script are as follows :
    1. Create a new command using multiple set of commands.
    2. For automating many aspects of computer maintenance, for example create 100 user accounts; delete all size 0 files, installation of new software etc.
    3. Data backup
  • As such there are no limitations on its usage; a user may use it for any purpose that he wants.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

Question 6.
Choose the most appropriate option from these given below :

1) In how many modes Vim editor works ?
(A) One
(B) Two
(C) Three
(D) Four
Answer:
(C) Three

2) Which of the following statement is true for Gedit ?
(A) It is a Command line editor.
(B) It is a Graphical editor.
(C) It is a not an editor.
(D) It is available with KDE Desktop environment.
Answer:
(B) It is a Graphical editor.

3) :wq in Vim editor is used for which of the following activities ?
(A) To save file and remain in editing mode
(B) To save file and quit editing mode
(C) To quite editing mode without saving changes made in the file
(D) All of the above
Answer:
(B) To save file and quit editing mode

4) Which of following keys is not used to go into insert mode of the Vim editor ?
(A) o
(B) i
(C) a
(D) cw
Answer:
(D) cw

5) Which of the following keys are used to delete a line ?
(A) ce
(B) ge
(C) dd
(D) d$
Answer:
(C) dd

6) Which of the following statements is used to search for phrase in the file ?
(A) :set is
(B) :help cmd
(C) :!cmd
(D) /phrase<ENTER>
Answer:
(D) /phrase<ENTER>

7) Which of the following syntax is used to substitute all occurrences of phrasel with phrase2 in the entire file without asking for user confirmation ?
(A) %s/phrasel/phrase2/g
(B) %s/phrasel/phrase2/gc
(C) :s/phrasel/phrase2/g
(D) :s/phrasel/phrase2/gc
Answer:
(A) %s/phrasel/phrase2/g

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

8) Which of the following character is used for commenting a line in a shell script ?
(A) *
(B) %
(C) $
(D) #
Answer:
(D) #

9) Which of the following symbol instructs a shell script to extract the value of a variable ?
(A) *
(B) %
(C) $
(D) #
Answer:
(C) $

Computer Class 11 GSEB Notes Chapter 7 Vim Editor and Basic Scripting

Working with Vim Editor

  • cat command is used to create a file.
  • The cat command although it allows us to create a file is not a good option to use when creating a shell script.
  • Text editors like pico,nano, vi or Vim ,ed and others are generally best suited for creating text file.
  • Gedit is a graphical editor available with GNOME desktop environment.
  • Kwrite is a graphical editor available with KDE desktop environment.
  • Full form of Vim is Vi Improved.
  • The Vim is a text editor.
  • Vim is written by Bram Moolenaar.
  • Vim was first released publicly in 1991.
  • Vim is enhanced version of the vi editor distributed with most UNIX systems.
  • Vim is a highly configurable text editor built to enable efficient text editing.
  • The Vim editor can be used from both a command line interface and as a standalone in a graphical user interface.
  • We will use Vim editor which is visual display editor to write the shell script.
  • Vim editor is available with almost all Unix and Linux flavours.
  • To work with the Vim editor we will have to initiate it first.
  • Open a new Terminal Window.
  • Vim editor can be opened in two ways :
    1. Type vi at the prompt and press Enter key.
    2. Type vi followed by a file name and press Enter key.
  • Following figure shows the Vim editor interface when we don’t specify a file name.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 6

  • It is good option to start the Vim editor by specifying a filename. Type the command given below :
  • $vi first_vim_file
  • And press Enter key,the command when executed will open the editor as shown in following figure.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 7

  • When we open new file it is filled with tildes (~) on the left side of the screen (as seen in figure).
  • The tilde (~) symbol indicates that the lines are yet to be used by the editor.
  • The cursor appears in the top left corner of the screen.
  • There is some text visible on the last line.
  • The last line is known as command line.
  • Command line displays the name of the file along with the information about the total number of lines and columns within the file.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

Creating a File in Vim

  • Let us now learn how to create a simple text file using the Vim editor.
  • Type vi followed by a file name and press Enter key :
    1. Execute the command given below to open the editor interface.
  • $vi about_Gandhiji :
    1. To enter text in the file the editor should be in insert mode.
    2. The most commonly used commands to get into insert mode are ‘a’ or ‘i’.
    3. Press ‘i’ and the editor will be in the insert mode. Then type the contents as given in the box below:

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 8

Moving Around in the Document

  • The arrow keys are used to move the cursor in up,down,left and right direction.
  • In insert mode we cannot do anything except for typing the text. So arrow keys will not give us
    expected result.
  • When using the Vim editor we need to use some special keystrokes to move within the document after going to the command mode.
  • Once in command mode we can also use the arrow keys to move within the document.
  • Following table lists the keystrokes that are used to navigate within the documents.
Command Usage
h Moves cursor left
l Moves cursor right
j Moves cursor down
k Moves cursor up
Spacebar Moves cursor right one space
-/+ Keys Move cursor down/up in first column
CTRL + d Scroll down one half of a page
CTRL + u Scroll up one half of a page
CTRL + f Scroll forward one page
CTRL + b Scroll back one page
M Move the cursor middle of the page
H Move the cursor to top of the page
L Move the cursor to bottom of page
$ Move the cursor to end of line
) Move the cursor to of next sentence
( Move the cursor to beginning of current sentence
G Move the cursor to end of file
W Move the cursor one word at a time
Nw Move the cursor ahead by N number of words
B Move the cursor back a word at a time.
b Move the cursor back a word at a time.
Nb Move the cursor back by N number of words
e Move the cursor to end of word
gg Move to first line of file
0 Move to the beginning of the line.

Keys to Navigate in File

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

Editing the Document

  • Editing the document is one of the most common operations that a user would perform once the document is created.
  • In editing the file
    1. It is possible to insert or delete any data at a specific position as per our needs.
    2. We can also replace contents or change the case of individual characters if required.
  • A user needs to toggle between the command and the insert mode when we edit a document.
  • Let us try to add the contents given in the box below to the file about_Gandhiji.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 9

  • To edit the document we need to open the file using vi command, so execute the following command:
  • $vi about_Gandhiji again :
  • Note that the blinking cursor is visible on the first character at top left.
  • In normal cases we would have used the T option to enter the insert mode, but we need to append
    the contents at the end.
  • Therefore type G and you will observe that the cursor gets positioned at last line.
  • The position of the cursor will depend upon how the file was initially saved.
  • Typing G may Place the cursor in a new line after the last line( case when Enter key was pressed before saving the file) or the cursor will be placed on the first character of the last line( case when Enter key was not pressed before saving the file)
  • If the cursor is placed at new line,press ESC and then ‘I’ and start typing the contents. Incase if the cursor is placed on the first character of the last line ,then press ‘o’.
  • This will take you to a new line and start typing the contents.
  • In case of any errors in typing we may use the Backspace key and go back one cursor position at a time to correct the error.
  • Once the editing is over press ESC key and type :wq to go to the last line mode,save the file and end the Vim session.
  • Following figure shows the look of the editor after the new contents have been added.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 10

  • Following table lists commands to perform various editing operations on any document.
Command Usage
u Undo last change
U Undo all changes to entire line
dd Delete single line
Ndd Delete N number of lines
D Delete contents of line after cursor
C Delete contents of line after cursor and insert new text. Press ESC key to end the insertion
dw Delete one word
Ndw Delete N number of words
cw Change word
x Delete the character under the cursor.
X Delete the character before the cursor (Backspace).
r Replace single character
R Overwrite characters from cursor onward
s Substitute one character under cursor and continue to insert
S Substitute entire line and begin to insert at beginning of line
~ Change case of individual character
. Repeat last command action.

Commands to Perform Editing

  • The Vim editor allows us to copy text from our file into temporary buffer and vice-versa.
  • Each buffer acts like temporary memory, more commonly known as “clipboard”.
  • Following table lists commands used for capturing(copying) and pasting data.
Command Usage
Yy Copy single line (defined by current cursor position) into the buffer
Nyy Copy N lines from current cursor position into the buffer
P Place (paste) contents of buffer after current line defined by current cursor position.

Commands to Capture and Paste

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

Searching and Replacing Text

  • The Vim editor allows to use special commands to search text or a regular expression within the file.
  • The Vim editor also allows substitution of a word in place of another using command.
  • Following table lists commands used for performing search or replace operation withing a file.
Command Usage
/ Search for text in a forward direction
? Search for text in a backwards direction
n Search again in the same direction
SHIFT + n Search again in the opposite direction
f Press f and type the character to be searched. The cursor will move to that character on the current line.
SHIFT + f Similar to f but searches in backward direction
t Similar to f except that it moves the cursor one character before the specified character.
SHIFT + t Similar to t but searches in backward direction
: s / old_string / new_string Substitutes new_string for the first occurrence of the old_string in the current line
: s / old… string / new_string/’ g Substitutes new_string for all the occurrences of the old_string in the current line
: % s / old_string / new_strin g / g Substitutes new_string for all the occurrences of the old_string in the whole file
: % s / old_string / new_string / gc Substitutes new_string for all the occurrences of the old_string in the file, but asks for confirmation before substituting the new_string

Commands to Perform Search and Replace Operation

  • Let us try to use some of the Table commands in the about_Gandhiji.
  • Let us replace all the occurrences of the word “Gandhi” with word “Gandhiji”.
  • To perform this operation first open the file using the command about_Gandhiji, then go to the last line mode by pressing the ESC key and execute the command given below :
    :%s/Gandhi/Gandhiji/g
  • Let us understand the above command :
    1. %s indicates we are trying to replace a string.
    2. The term “Gandhi” refers to the old string this is to be replaced .
    3. The term “Gandhiji” refers to the new string.
    4. The option “g” indicates that we have to substitute all the occurrences of the term “Gandhi” with the term “Gandhiji” in the whole file.
  • The output of this command is shown in following figure.
  • Observe that it also shows how many occurrences have been replaced.
  • If we want the change to reflect in the file, we need to save the file.
  • If we quit without saving then the changes will not be reflected in the file.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 11

Executing Linux Commands Through Vim

  • It is possible to execute the Linux commands from within the Vim editor.
  • To execute any Linux command we need to type the exclamation (!) symbol before the command. 4 Let us see the examples.
  • For example if we want to see the current working directory then perform the following steps :
    1. Open the Vim editor by typing vi on the command prompt.
    2. Go to the last line mode^by pressing ‘ESC’.
    3. Type !pwd
    4. Press Enter key.
  • We will be able to seee current working directory following figure shows the operation and its output.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 12

  • If we want to add the current date in a new line from the current cursor position within a file execute the following steps :
    1. Open the Vim editor by typing vi on the command prompt.
    2. Go to the last line mode by pressing ‘ESC’.
    3. Type r !date
    4. Press Enter key.
  • The r option allows us to insert data in the file

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

Shell Script Variables

  • The process of shell scripting is almost similar to the process of writing programs in a higher level language.
  • One of the most common features of higher level programming is provision of variables.
  • Variables are entities wherein we can store or edit a value.
  • The value stored in the variable can also be reused or changed as per users need.
  • Shell script variables like any other programming language variables are integral part of shell scripting.
  • A variable when used in a shell script allows us to assign a value to it or accept its value from the user.
  • Let us display the value assigned to the variable on the screen using echo command. Let us write a
    small script that shows the use of variable.
  • Type the following script in Vim editor and name it as script4.sh

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 13

    1. First line begins with symbol ‘#’ so it is a comment.
    2. The second line has clear command which clears the screen contents before giving the output of the script.
    3. The third line variable named subject is define and is also assigned a value “Computer Science”. To assign a value to a variable = (equal to) operator is used. While assigning value to the variable if the string contains white space in between two words we need to enclose it within double quotes. Here in this example there is white space between the two words computer and science. Therefore it is enclosed in double quotes.
      Let us conclude it as “The statement subject=”Computer Science” first creates a variable named subject and then assigns it a value “Computer Science”.
    4. The fourth line displays the message on the screen. The ‘$’ symbol preceding the variable name subject instructs the shell to extract the value stored or assigned in the variable.
    5. Figure shows the output of the script when it is executed.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 14

    1. A user needs to take care that there should not be any space on either side of the equal to (=) symbol at the time of assigning a value.
    2. If due to some reasons a space occurs at either side, the shell will interpret the string after the space as a command. This may give unexpected outputs.
    3. If we reuse this variable again (i.e. if we give same name to the variables then), the old value stored in it will be overwritten. Let us try to understand this by writing a simple script given in the box:
# Script 5: Shell script to show use of variables .
clear
subject="Computer Science"
echo $subject is easy to learn.
subject="Economics "
echo $subject is easy to learn.
  • Save the script as script5.sh and observe the output after executing it.
  • We need to follow the rules mentioned below when defining a variable in a shell script :
    1. A variable name can consist of alphabets, digits or an underscore (_)
    2. No special character other than underscore allowed as part of variable name.
    3. The first character of a variable name must either be an alphabet or an underscore.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 15

  • If the shell is unable to understand a word as a variable it will interpret it as a Linux command.

User Interaction and Shell Script

  • It is possible to assign value to variables defined in the shell script using the read command.
  • The read command expects the user to key in the data on the standard input device,it then takes all
    the contents that we type and stores it in the variable name supplied to it as an argument.
  • Let us rewrite script 5 to accept the user name and subject name from the user. Save the following code with a file name script6.sh.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 16

    1. First line begins with symbol ‘#’ so it is a comment.
    2. The second line has clear command which clears the screen contents before giving the output of the script.
    3. The third line will display a message “Enter your name:”
      Take note that -n option along with the echo command. This option instructs the echo command not to print a new line after the message is displayed. The echo command by default inserts a new line after displaying the message passed to it as an argument.
    4. The fourth line waits for the user to enter its name. Pressing of Enter key indicates end of entry, so be careful that it is pressed only after the name has been typed. In case we press Enter key without typing anything the script will assign NULL value to the variable and move to next command.
    5. The fifth line will display a message “Enter name of a subject:”
    6. The sixth line waits for the user to enter its subject name, and pressing of Enter key indicates end of entry.
    7. The last line displays the message.
  • For example we execute this script by providing name as Vidita and subject as Computer Science then
    the Figure will be output of the script.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 17

  • As we are accepting the values of both the variables from the user, the output will change according to what user enters every time we execute the script.
  • Let us write one more script that accepts a file name from the user and display the total number of lines in that file. The code of the script is shown herewith save it as script7.sh.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 18

    1. First line begins with symbol ‘#’ so it is a comment.
    2. The second line has clear command which clears the screen contents before giving the output of the script.
    3. The third line will display a message “Enter your name:” using echo command and -n option.
    4. The fourth line accepts the name of file from the user.
    5. In fifth line fname stores the name of the file so cat $fname displays the content of that file which is piped to wc -1 command which counts number of lines of the content of the file and the output of the file is displayed as Figure when executed.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 19

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting

Shell Arithmetic

  • Till now we have assigned strings (set of alphabet, digit or special characters) to a variable. We can also assign only numeric values to the variable and perform operation with them. Let us write a shell script that accept two numbers and perform addition of these numbers. The code of the script is shown herewith save it as script8.sh.
# Script 8: Script to add two numbers
echo -n "Enter first number: "
read num1
echo -n "Enter second number: "
read num2
sum = 'expr $numl + $num2'
echo "The addition of $numl and $num2 is $sum"
    1. The term expr means expression.
    2. The contents written after expr are assumed to be operands and operators of an expression.
    3. Figure shows the different output of the script when it is executed twice.
    4. We are able to see the different outputs in one screen as we have not used the clear command in this script.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 20

  • Note :
    1. There should be one space between operator (+) and operands (Snuml, $num2).
    2. There should be no space before or after the assignment operator (= ).
  • We can also perform subtraction, multiplication, division and modular division by using the -.*, / and % operators respectively.
  • The expressions are evaluated as per the general norms of mathematics.
  • In case of tie between operators of same priority, preference is given to the operator which occurs first.
  • To force one operation to be performed earlier than the other, we can enclose the operation in
    parenthesis.
  • For example, in the expression will be evaluated first as it is enclosed within parentheses. Observe that we have preceded the symbol as well as the left and right parentheses by a back slash character (\).
  • Note : We need to prefix the multiplication (*) symbol with backslash (\) character when finding product of two numbers. Otherwise the shell will treat the (*) symbol as a wildcard character.
  • Let us write a shell script that will accept a birth year from the user and display users current age in years. The code of the script is shown herewith save it as scripts).sh.
# Script 9: Script to calculate age of user in years
echo -n "Enter year of your birth: "
read byear
cyear='date | tr -s ’ ’ | cut -d " " -f 6'
age='expr $cyear - $byear'
echo "You are $age years old as of today."
    1. The tr command with -s option (tr -s ’ ‘ Squeezes all the multiple spaces in output of date command to a single space.
    2. In the output of the date command year is displayed in the 6th column. So we have filtered sixth column using cut command with -d and -f options, -d ” ” specifies the delimiter of the column is space . -f 6 specifies the field (column) number six is to be extracted.
  • Following figure the different output of the script when it is executed.

Computer Class 11 GSEB Solutions Chapter 7 Vim Editor and Basic Scripting 21

Leave a Comment

Your email address will not be published. Required fields are marked *