Students frequently turn to Computer Class 11 GSEB Solutions and GSEB Computer Textbook Solutions Class 11 Chapter 8 Advanced Scripting for practice and self-assessment.
GSEB Computer Textbook Solutions Class 11 Chapter 8 Advanced Scripting
Question 1.
Explain conditional execution in shell script with proper example.
Answer:
Decision Making Tasks
- Following four decision making instructions are available in Linux which can be used in shell script:
- if-then-fi
- if-then-else-fi
- if-then-el if-then-else-fi
- case-esac
- These above four constructs in shell scripts allows us to perform decision making.
- Till now we have written sequential shell script. Now let us understand where and how to use each
of the above decision making instruction :
Decision Making Instruction-1 (if – then – fi )
Example 1 : If student has greater than 35 percentage display “Result : Pass” - Solution : In this scenario use above construct 1 (if – then – fi ) while writing Shell Script.
- Now let us write a shell script to understand (if – then – fi ) decision making instruction .
- Let us write a shell script that creates a directory. It accepts the name of directory from the user .If file
or directory of same name exists then gives proper message.
#Script 12: Script to create a directory with appropriate message. echo -n "Enter directory name: " read dirname if [ -d $dirname -o -f $dirname ] then echo "A File or Directory with the name $dirname already exists.” exit 0 fi mkdir $dirname echo "Directory with name $dirname created successfully."
- Save the script as script12.sh.
- The if statement of Linux is concerned with the exit status of a test expression.
- The exit status indicates whether the command was successfully executed or not.
- The exit status of command is 0 if it has been executed successfully; otherwise it is set to 1.
- The -d, -f, -o options used in the script are file operator which are discussed later in the chapter.
Take care of the following points while writing is construct :
- The condition in the above script is enclosed in a square bracket.
- There should be one space after opening square bracket and one before closing square bracket.
- If the condition is evaluated to true then statements typed inside then block will be executed otherwise not.
- The end of the if statement is indicated by fi statement.
- Also note that the then keyword should be typed below if statement else we will get error.
Decision making instruction 2 (if – then – else – fi ) - Example-2: If student has greater than 35 percentage display “Result: Pass” otherwise display “Result: Fail”
Solution : In this scenario use above construct 2 (if – then – else – fi) while writing Shell Script. - Let us see another example.
- It is a normal practice to copy a file and keep in it another directory (may be for the purpose of backup). The user many times gets confused whether both the files are same or different.
- So let us write Scriptl3.sh a shell script that compares such files.
- The script when executed , compares both the files using the cmp command.
- Based on the output of the cmp command, it displays respective appropriate message.
- To keep the script simple as of now we have used absolute paths for directory (user can convert it relative path).
#Script 13: Script to compare files. echo -n "Enter a file name: " read filename if cmp ,/$filename ./backup/$filename then echo "$filename is same at both places." else echo "Both $filename are different." fi
- Let us understand the above script in brief :
- Here we first accept a file name from the user.
- To keep the script simple as of now we have used absolute paths for directory (user can convert it relative path).
- We have also assumed that the file names at both the locations are same. Following figure shows the output of the script.
- Here we have executed the script twice.
- In the first run both the files contents are same hence we get the message that both files are same.
- And in the second run both the files contents are different hence we are getting the message that files
are different.
Decision making instruction 3 (if – then – elif – then – else – fi ) - Example 3 : If student has greater than 70 percentage display “Result : Distinction”,
If student has percentage between 60 and 70 display “Result : First Class”,
If student has percentage between 50 and 60 display “Result : Second Class”,
If student has percentage between 40 and 50 display “Result : Pass Class”
otherwise display “Result : Fail” - Solution : In this scenario use above construct 3 (if – then – elif – then – else – fi) while writing Shell Script.
- Let us understand this decision making instruction by writing a shell script.
- Write Shell script named as scriptl4.sh to welcome the user that has logged in the system. Display proper welcome message (Good morning. Good afternoon or Good evening depending on the time the user has logged in).
#Script 14: Script to display welcome message to the user. clear hour=' date +"%H" ' usrname= 'who am i | cut -d ” ” -f 1' if [ $hour -ge 0 -a $hour -It 12 then echo "Good Morning $usrname, Welcome to Ubuntu Linux Session." elif [$hour -ge 12 -a $hour -It 18,J then echo "Good Afternoon $usrname, Welcome to Ubuntu Linux Session." else echo "Good Evening Susrname, Welcome to Ubuntu Linux Session." fi
- Following figure shows the output of the script
Question 2.
Explain case statement of shell script with the option of pattern list.
Answer:
The Case Statement
Decision Making Instruction-4 (case – esac) :
- The if-then-elif-then-else-fi statement looks clumsy as number of comparison grows.
- The alternate option for checking such conditions is to use a case statement.
- Example-4 :If user enters 1 then display current directory
If user enters 2 then display user who has logged in
If user enters 3 then display today date and time
If user enters 4 then creates a directory
If user enters 5 then moves a file
If user enters 6 then copies a file
Otherwise displays “Invalid Input” - Solution : In this scenario use above construct 4 (case – esac ) while writing Shell Script.
- Let us write a script name scriptl8.sh that allows us to accept a choice from the user and perform
different file operations based on the entered choice.
# Script 18: Script to perform various file and directory operations. echo "1 - Display Current Dir " echo "2 - Make Dir " echo "3 - Copy a file ” echo "4 - Rename a file " echo "5 - Delete a file ” echo "0 - Exit " echo -n "Enter your choice [0-5] : " read choice case $choice in 1) echo $pwd ;; 2) echo -n "Enter name of the directory to be created: " read dname if [ -d $dname ] then echo "Directory with the name $dname already exists." exit 0 else mkdir $dname echo "Directory $dname created successfully." fi ;; 3) echo -n "Enter source file name : " read sfile echo -n "Enter destination file name : " read dfile cp -u $sfile Sdfile ;; 4) echo -n "Enter old file name : " read oldf echo -n "Enter new file name : " read newf mv $oldf $newf ;; 5) echo -n "Enter file name to delete : " read fname rm $fname ;; 0) exit 0 ;; *) echo "Incorrect choice exiting script." esac
Let us understand the above script
- Note that for each operation that we need to perform we have written different section.
- When a user enters a numeric value between 0 and 5 it is assigned to the variable choice.
- The case statement extracts the value of variable choice, the control is transferred to the section with
a matching value specified before the closing round brackets. - All the statements written within that section are executed till two semicolons (;;) are encountered.
- Once these semicolons are encountered the control is transferred to the line after the end of the case statement.
- The end of case statement is specified by esac keyword.
- If user enters any value that does not match any of the case value specified, then the control is transferred to the section that has asterisk (*) as its value.
- If specified, this section allows a user to exit the script or perform additional processing after displaying an appropriate message.
- Figure shows us different output of script 18.
The syntax of case statement is:
Note :
- We can assign numeric, character or string values to the variable that accepts the choice.
- In case we assign string values then within the case it should be enclosed between single quotes.
- For example if we accept string First then within the case- statement it should be mentioned as ‘First’.
Question 3.
Explain the use of while loop.
Answer:
Repetition : While Statement
- We can also use the while statement for looping.
- It repeats the set of commands specified between keywords do and done statements as long as the condition specified as an expression is true.
- Let us write a script that allows administrator to remove a specified number of files from a directory.
#Script 21: Script to delete specified number of files from a directory. clear echo -n "Enter the name of directory from where you want to delete: " read dname if [ -d Sdname ] then cd $dname echo -n "Enter the number of files you want to delete: " read fdel ctr=1 while [ $ctr -le $fdel ] do echo -n "Enter the name of the file to be deleted: " read fname if [ -f $fname ] then rm $fname echo "Sfname deleted successfully." else echo "File with name Sfname not found." fi ctr='expr $ctr + 1' done else echo "Directory Sdname does not exist." fi cd ..
- Save the script as script21.sh
- Let us understand how the script works.
- Initially the user is prompted to enter a directory name. The dname variable is assigned this value.
- Then we check whether such a directory exists or not. If it exists we change to that directory and ask user the number of files he wants to delete.
- Then we start a while loop that finds the files to be deleted.
- If the file is found we delete it else we display a message indicating file not found.
- The loop is continued till the value of variable ctr is less than or equal to the number of files specified
by the user. - Once the operation is over we go back to the parent directory.
- The syntax of while loop is shown below:
while [ test condition ] Do command or set of commands done
Question 4.
Explain the use of until loop.
Answer:
Repetition : Until Statement
- Another method to execute repetitive statements is to make use of the until statement.
- The until loop is similar to the while loop.
- However, the until loop executes till the condition is false and the while loop executes till the condition is true.
- Script 19 is a menu driven script demonstrating until-loop, to display list of files in a current directory, changing password, displaying current date and time and searching a word from a file.
#Script 22: Script to perform operations till user decides to exit. choice=y until [ $choice = n ] do dear echo " echo " Choose an option from menu given below " echo " ................... " echo "a: List of files and directories in a current directory." echo "b: Display current working directory" echo "c: Display current date and time" echo "d: Searching a word from file" echo "e: Exit" echo " " echo " " echo -n "Enter your choice [a-e]: " read ch case $ch in a) Is -l b) echo "You are working in 'pwd'" ;; c) echo "Current date and time is 'date'" ;; d) * echo -n "Enter the word to be searched: " read word echo -n "Enter the file name from which the word is to be searched : " read file if [ -f $file ] then grep $word $file else echo -n "File with name $file does not exist." fi ;; e) exit ;; *) echo "Incorrect choice, try again.." ;; esac echo -n "Do you want to continue? : " read choice done
- Save the script as script22.sh.
- When user executes the script he will be shown a menu and asked to enter a choice.
- Depending on the choice entered an action from the case will be executed.
- Enter different choice each time and see the output.
- The script will keep on executing till user enters e as a choice in which case the exit statement within the case is executed or he enters n when the question “Do you want to continue ?” is asked.
- Figure shows the output of script 22.
Question 5.
Choose the most appropriate option from those given below :
(1) Which of the following command is used to set the file permission as executable ?
(A) grep
(B) chmod
(C) ls
(D) x
Answer:
(B) chmod
(2) Which of the following symbol is used to break the flow of control in the case statement ?
(A) **
(B) ;;
(C) ++
(D) >>
Answer:
(B) ;;
(3) Which of the following keyword specifies the end of the case statement ?
(A) end-case
(B) end case
(C) esac
(D) stop-case
Answer:
(C) esac
(4) Which loop literates till the condition evaluates to true ?
(A) while
(B) until
(C) for
(D) case
Answer:
(A) while
(5) Which of the following allows us to specify a list of values in its statement ?
(A) while
(B) until
(C) for
(D) if
Answer:
(C) for
(6) In case structure, which of the following character denotes default case ?
(A) *
(B) +
(C) d
(D) All of the above
Answer:
(A) *
(7) Which of the following statement is true for testing whether the file is read only or not ?
(A) test -read filename
(B) check -read filename
(C) test -r filename
(D) check -r filename
Answer:
(C) test -r filename
(8) Which of the following indicate the end of if condition in shell script ?
(A) end-if
(B) fi
(C) } (closing curly bracket)
(D) It does not have any end statement
Answer:
(B) fi
(9) Which of the following operator is used for less than comparison in Linux ?
(A) <
(B) lessthan
(C) lt
(D) -It
Answer:
(D) -It
(10) Which of the following can be used in place of square brackets used in if condition ?
(A) Curly braces
(B) Test command
(C) Check command
(D) All of the above
Answer:
(B) Test command
Computer Class 11 GSEB Notes Chapter 8 Advanced Scripting
Finding Process Id
- In Linux all programs are executed as processes .
- We can view or stop a process.
- To see the processes associated with the current shell we can issue the ps command without any parameters.
- We can view the process of all the users by using theps -ef command.
- Figure shows the processes running on our system.
- Following table gives the meaning of the columns listed in figure.
Column Name | Description |
UID | Name or number of the user who owns the process. |
PID | A unique numeric process identifier assigned to each process. |
PPID | Identifies the parent process id, the process that created the current process. |
STIME | The start time for the current process. |
TTY | Identifies the terminal that controls the current process. |
TIME | Identifies the amount of CPU time accumulated by the current process. |
CMD | Identifies the command used to invoke the process. |
Explanation of Columns Displayed in ps-ef Command
- Defination :
(1) Process : It is a program loaded into memory and running.
(2) PID : Each process when started has a unique number associated with it known as process id (PID).-
- Let us write a scriptlO.sh that finds number of process run by a particular user.
-
#Script 10: Script to find out how many processes a user is running, clear echo -n "Enter username: " read username cnt='ps -ef | cut -d n " -f 1 | grep -o $username | wc -w' echo "User Susername is running $cnt processes."
-
- Let us try to understand the working of this script.
- The first command clears the content on the screen.
- Second line displays message for the user to enter a user name.
- The read command then assigns the string read from the keyboard to variable username.
- Fourth line has combined four commands namely ps, cut, grep and wc using pipe.
- The ps -ef command displays list of processes being run by all the users of the system. Its output is then given to the cut command.
- The cut command extracts the first field (username) from the output given by ps -ef command.
- The extracted list of first field is then given to the grep command. The grep command finds all the users that match with the value that is extracted from variable username.
- This matched list is then given to the wc -w command that counts the occurrence of the given username.
- Finally this word count is assigned to variable cnt.
- The last command then displays how many processes a user is running.
- Following figure shows the sample output of the script.
- Let us try to understand the working of this script.
-
- To remove the process from memory we use the kill command.
- For example if we issue a command
Skill -9 211 - Then the process with PID=211 will be forcibly removed from the memory.
- Write following code as scriptll.sh that accepts user name as a command line argument and tells us how many terminals that user is usingand observe its output.
#Script 11: Script to find out how many terminals a user has opened. cnt='who | cut -d " ” -f 1 | grep -o $1 | wc -w’ echo "User $1 has opened $cnt terminals"
-
- Compare Script10.sh and Script11.sh
- Command line argument is used in Script11.sh.
- $1 in Script11.sh refers to a command line argument.
- Defination :Command line arguments : Linux stores the values provided through command line in dollar variables, named $1, $2, $3 and so on. First argument will be stored in $1, second in $2, third in $3 and so on till $9. These arguments are known as command line arguments.
- To execute this script type the command as follows :
- Ssh scriptlLsh administrator
-
- Let us try to understand the working of this script.
- The first command is a comment.
- Second statement has combined four commands namely who, cut, grep and wc using pipe.
- The who command displays list of all users that have logged into the system. Its output is then given to the cut command.
- The cut command extracts the first field from this output. The extracted list of first field is then given to the grep command.
- The grep command then finds out all the users that match with the entered command line argument value ($1 = administrator). This matched list is then given to the wc command.
- The wc command that counts the occurence of the given word (username).
- Finally this word count is assigned to variable cnt.
- The last command then displays how many terminals a user has opened.
- Let us try to understand the working of this script.
The Test Command
- Linux provides test command which can be used in place of square brackets used in previous scripts.
- Let us write script to check whether a user has created more than some specified files in a given month
or not.
#Script 15: Script to see whether user has created more than specified files in a month. clear cnt='Is -l | grep -c [-]"$1"‘ echo -n "Enter number of files : " read nfile if test Sent -gt Snfile then echo "You have created more than $nfite files in the month of $1" else echo "You have not created more than $nfile files in the month of $1" fi
- Let us understand the above script.
- First statement has comment.
- Second statement has clear command which clears the screen.
- In third statement we have defined a variable named cnt.
- This variable is assigned the total count of the files created in a specified month.
- To find out the number of files we have used two commands namely Is and grep.
- The Is -1 command is used to display long listed details of files and directories.
- Its output is then given to the grep command that matches regular expression [-]”$1″.
- The month is specified as two digit numeric value and accepted through command line argument assigned to $1.
- Fourth statement displays a message to “Enter number of files
- variable nfile stores the value of number of files that we want to compare with.
- Now let us understand if block.
- The -gt option in the test indicated greater than comparison.
- Here we are checking whether the value of cnt is greater than the value of nfile or not.
- If the value of cnt is greater than the value of nfile we print the message “You have created more than Snfile files in the month of $1”, where Snfile and $1 are replaced with appropriate values.
- Otherwise we print message “You have not created more than Snfile files in the month of $1”.
- Figure shows the output of the script when we issue a command shown below on the command prompt.
- $sh scriptl5.sh
- The if statement can work with numerical values, strings and files.
- In turn the tests performed are known as numerical test, string test and files test respectively.
- Observe that we have used options like -d, -f. -o, -a, -ge, -It and -gt in the scripts created so far. All these options allow us to perform various types of condition matching.
Relational Operators
- The numerical test is performed using relational operators.
- The options -ge, -It and -gt refers to relational operators.
- These operators are used to compare values of two numeric operands.
- Table lists the relational operators that can be used in shell scripts along with their usage.
Operator | Usage |
-gt | greater than |
-It | less than |
-ge | greater than or equal to |
-le | less than or equal to |
-ne | not equal to |
-eq | equal to |
Relational operators
Logical Operators
- To combine conditions we make use of logical operators.
- Table lists the logical operators along with their usage.
Operator | Usage | Minimum conditions that can be combined | Output |
-a | AND | Two | True if both conditions are true, false otherwise |
-o | OR | Two | True if any one condition is true, false only if both conditions are false |
i | NOT | One | Converts true to false and vice versa |
Logical operators
File Operators
- File operators that allows us to check the status of a file.
- These operators are used as a condition within the if statement.
- By using file operators we can come to know whether a specified name is an ordinary file or a directory.
- We can also find out the status of file permissions using them.
- Table lists usage of these options.
Condition Tested | Output |
-s name | True if a file with the specified name exists and has size greater than 0. |
-f name | True if a file with the specified name exists and is not a directory. |
-d name | True if a directory with the specified name exists. |
-r name | True if a file with the specified name exists and the user has read permission on it. |
-w name | True if a file with the specified name exists and the user has write permission on it. |
-x name | True if a file with the specified name exists and user has execute permission on it. |
File Test Conditions
- Let us write a script named as scriptl6.sh that allows administrator to check the file size and know what permissions are allocated to the file.
#Script 16: Script to check file size. echo -n "Enter a file name: " read fname if [ -s $fname -a -w $fname ] then echo $fname has size greater than 0 and user has write permission on it. else echo $fname has size 0 or user does not have write permission on it. fi
- Here the statement if [ -s $fname -a -w $fname ] has multiple conditions. The result of the if statement is evaluated when both the conditions give us some output. Table lists the value that can be generated as output when the if statement is evaluated and figure shows different output of the script.
- The if-then-fi and if-then-else-fi statements used so far allow us to test limited set of conditions.
- In case a user needs to perform more number of tests these statements may not be of much help.
- In such cases we may use the if-then-elif-then-else-fl or the case statement.
- Let us write a script named as that accepts three files from user and displays the file which has maximum size.
#Script 17: Script to find the file with the maximum size. clear echo -n "Enter name of first file: " read fname1 echo -n "Enter name of second file: " read fname2 echo -n "Enter name of third file: " read fname3 fsize1='wc -c $fname1 | cut -d " " -f 1' fsize2='wc -c $fname2 | cut -d " " -f 1' fsize3 = 'wc -c $fname3 | cut -d " " -f 1' echo Size of $fname1 = $fsize1 echo Size of $fname2 = $fsize2 echo Size of $fname3 = $fsize3 if [ $fsize1 -eq $fsize2 -a $fsize1 -eq $fsize3 ] then echo "All files have same size" elif [ $fsize1 -gt $fsize2 -a $fsize1 -gt $fsize3 ] then echo "$fname1 has maximum size." elif [ $fsize2 -gt $fsize1 -a $fsize2 -gt $fsize3 ] then echo "$fname2 has maximum size." else echo ”$fname3 has maximum size." fi
- Let us understand the above script.
- The six statements after the clear command are used to accept the file names from the user.
- The next three statements calculate size of the files, later these sizes are displayed to the user.
- Finally using the if condition, the script finds out the file that has maximum size.
- Figure shows the output of the script.
Handling Repetition
- Suppose we want to clean disk space. There can be many zero sized file and therefore many files have to be deleted . Thus process of finding zero sized file and deleting it is a repetitive task. So we would use loop. Let us use for loop in shell script.
#Script 19: Script to delete zero sized files, echo -n "Enter directory name : " read dname if [ ! -d $dname ] then echo Directory $dname does not exist. else ctr=0 for i in 'find "$dname/" -type f -size 0c' d0 rm $i echo File $i" : deleted" ctr="expr Sctr +1 done if [ $ctr -gt 0 ] then echo "$ctr zero sized files have been deleted." else echo "No zero sized files present in directory." fi fi
- Observe that in this script we have used a statement for i in ‘find “$dname/M -type f -size 0c’
- This statement is used to repeat some actions again and again. Figure shows the output of script 19.
- At times while writing a computer program some task are repeated . Do we need to write the code for
the repeated task again and again ? Ans is No .Instead of writing code again and again we can define
the code once in ioop . - Definition : The process of repeating the same commands number of times is known as looping.
- Linux provides three keywords namely for, while and until that can be used to perform repetitive
actions. - Let us now understand each keyword in detail :
(1) For loop :
-
- The for loop allows us to specify a list of values in its statement.
- The loop is then executed for each value mentioned within the list.
- The general syntax of for statement is shown below:
for control-variable in value 1, value2, value3 Do command 1 command 2 command 3 Done
- Let us write another script that first creates a backup directory in the folder where the files are located. Then the files which needs backup are copied into it. The directory is then compressed and finally moved to a new location. The script written below performs this action.
#Script 20: Script to backup and compress desired files from current location. clear dat=' date + "%d_°/om_%Y"' bdir=backup_$dat if [ ! -d $bdir ] then mkdir $bdir else echo "Directory with name $bdir already exist." exit 0 fi echo -n "Enter the extension of the files to backup: ” read fextn ctr=0 for i in 'Is -1 *.$fextn' do cp Si ./$bdir ctr='expr $ctr + 1' done if [ $ctr -gt 0 ] then tar -czf $bdir.tar $bdir cd $bdir rm -r *.* cd .. rmdir $bdir echo "All files with extension .$fextn stored in $bdir.tar" else rmdir $bdir echo "No files with the extension found." fi
- Save the script as script20.sh.
- Let us understand how the script works.
- Initially we have defined two variables namely dat and bdir.
- The dat variable is assigned the value of current date in the specified format. For example if the current date is 21 February 2013 then variable dat will be assigned value 21_02_2013.
- The variable bdir is then assigned value backup_21_02_2013.
- Then we check whether such a directory exists or not.
- If it does not exist we create this directory otherwise we exit with the message saying that the directory already exists.
- If we create a directory then we ask the user to enter a file extension.
- The script looks for the files with specified extension in the current directory and if found”copies
them in the back-up directory. - Once all files are copied, the backup directory is compressed (packed) using, the tar command. The tar -czf $bdir.tar $bdir statement performs this operation.
- Here we create a tar file named backup_currentdate.tar.
- Then we empty the contents of the backup directory and delete it.
- In case we do not find any files with the extension specified we display appropriate message.
- The administrator if he wants now can move the compressed tar file to the location he desires.
- We can uncompress the tar file by using the command tar -xvf filename.
Functions in Script
- Functions are small subscripts within a shell script.
- They are used make the scripting more modular.
- Using functions we can improve the overall readability of the script.
- The function used in shell script do not return a value, they return a status code.
- Let us write a script that assists the user in finding out how many files were created on current date or when a particular file was last modified.
#Script 23: Script to show use of function. file_today(){ cur_date= 'date +',%Y-%m-%d'' cnt='ls -l tr | grep "$cur_date" | wc -I' echo "Current date is : " $cur_date echo "No. of files created today : "$cnt } Modified_today() { if [ -f "$I" ] then stat -c %y "$1" else echo ""$1" does not exist" fi } choice=y until [ $choice = n ] do clear echo " " echo " Choose an option from menu given below echo " " echo "a: List of files created today" echo "b: Display last file modification date." echo "c: Exit" echo " " echo " " echo -n "Enter your choice [a-c]: " read ch case $ch in a) file_today ;; b) echo -n "Enter a file name: read fname modified_today $fname ;; a) exit ;; *) echo "Incorrect choice, try again.." ;; esac echo -n "Do you want to continue? : " read choice done
- Save the script as script23.sh.
- Observe that in script 23 we have used two functions namely file_today() and modified_today().
- The opening and closing parenthesis after a variable name indicates that it is a function.
- When user enters a, function file_todayO that contains code for finding the files created on a current date is called and executed.
- Similarly when user enters b he is prompted to enter a file name.
- This name is then passed to function modified_today() that checks if the files exists or not.
- If the file exists its last modification date is displayed otherwise appropriate message is displayed.
- Figure shows the output of script 23.