1,234
edits
Changes
no edit summary
{{Admon/caution|DO NOT USE THIS VERSION OF THE LAB. This page will no longer be updated.|'''New version here:''' https://seneca-ictoer.github.io/ULI101/A-Tutorials/tutorial12<br />'''Andrew's students please go here:''' http://wiki.littlesvr.ca/wiki/OPS145_Lab_11}}
=ADDITIONAL SHELL SCRIPTING=
<br>
===Main Objectives of this Practice Tutorial===
:* Learn about additional logic control-flow statements if-else and Use the '''if-elif-else''' control flow statement in a shell script.
:* Learn additional uses of Use the '''for ''' loop control-flow statementusing a list with '''command substitution'''.
:* Learn Use the purpose of command substitution and how it can be used with control-flow statements'''while''' loop in a shell script.
:* List Use the '''exit''' and explain the purpose of several '''break''' statements in a shell script. :* Explain how to configure and use a '''.bashrc''' start-up filesfile.<br><br>
===Tutorial Reference Material===
|- valign="top" style="padding-left:15px;"
|colspan="2" |Course Notes'''Slides:'''<ul><li>Week 12 Lecture 1 Notes:<br>[https://ictwiki.cdot.senecacollege.ca/~murray.saululi101/uli101slides/ULI101-Week1212.1.pdf PDF] | [https://ictwiki.cdot.senecacollege.ca/~murray.saululi101/uli101slides/ULI101-Week1212.1.pptx PPTX]</li></ul>
| style="padding-left:15px;" |Additional '''Control Flow Statements* [https://www.tutorialspoint.com/unix/if-else-statement.htm if-else]'''
* [https://www.tutorialspoint.com/unix/if-else-statement.htm if-elif-else]
* [https://www.cyberciti.biz/faq/bash-for-loop/#:~:text=A%20'for%20loop'%20is%20a,files%20using%20a%20for%20loop. for Loop]
* [https://bash.cyberciti.biz/guide/While_loop while Loop]<br><br>'''Additional Statements:'''* [https://www.geeksforgeeks.org/exit-command-in-linux-with-examples/#:~:text=exit%20command%20in%20linux%20is,last%20command%20that%20is%20executed.&text=After%20pressing%20enter%2C%20the%20terminal%20will%20simply%20close. exit]* [https://www.geeksforgeeks.org/break-command-in-linux-with-examples/#:~:text=break%20command%20is%20used%20to,The%20default%20number%20is%201. break]
| style="padding-left:15px;"|'''Startup Files:'''
* [https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html Purpose]
* [http://www.linuxfromscratch.org/blfs/view/svn/postlfs/profile.html Examples]
|colspan="1" style="padding-left:15px;" width="30%"|'''Brauer Instructional Videos:'''<ul><li>[https://www.youtube.com/watch?v=XVTwbINXnk4&list=PLU1b1f-2Oe90TuYfifnWulINjMv_Wr16N&index=6 Bash Shell Scripting - Part 2]</li></ul>
|}
= KEY CONCEPTS =
====IF-ELIF-ELSE STATEMENT==== [[Image:if-elif-else.png|thumb|right|300px|Example of how an '''if-elif-else''' statement works.<br>(Image licensed under [https://creativecommons.org/licenses/by-sa/3.0/ cc])]] The '''elif''' statement can be used to perform additional conditional tests of the previous test condition tests '''FALSE'''. This statement is used to make your logic control-flow statement to be more adaptable.<br><br>''How it Works:''<br>If the test condition returns a '''TRUE ''' value, then the Linux Commands between<br>'''then ''' and '''else ''' statements are executed.<br><br>If the test returns a '''FALSE ''' value, then '''a <u>new</u> condition is tested again''',<br>and action is taken if the result is '''TRUE''', then the Linux Commands between<br>the '''then''' and '''else and fi ''' statements are executed.'''Additional elif statements''' can be used if additional conditional testing is required . Eventually, an action will be taken<br>when the final test condition is '''FALSE'''.<br><br>
''Example:''
<span style="font-family:courier;font-weight:bold;">num1=5<br>num2=10<br>if test $num1 –lt $num2<br>then<br> echo “Less Than”<br>elseelif test $num1 –gt $num2<br>then<br> echo “Greater Than”<br>else “Greater Than or Equal echo “Equal to”<br>fi</span><br><br>
''Example:''
<span style="font-family:courier;font-weight:bold;">num1=5<br>num2=10for x in $(ls)<br>if test $num1 –lt $num2do<br>then echo “Less Than”<br>elif test $num1 –gt “The item is: $num2<br>then<br> echo “Greater Than”<br>else echo “Equal to”x”<br>fidone</span><br><br>
===Additional Loop Statements=WHILE LOOP====[[Image:while-loop.png|thumb|right|170px|Example of how a '''while''' loop works.<br>(Image licensed under [https://creativecommons.org/licenses/by-sa/3.0/ cc])]]
<span style="font-family:courier;font-weight:bold">command1 answer=10<br>read –p “pick a number between 1 and 10: “ guess<br>while test $(command2)guess –eq 10<br>do read –p “Try again: “ guess<br>command1 [arguments from command2 output]done<br>echo “You are correct”</span><br><br>
'''for Loop using Command Substitution'Example 2:''
''Example:''<br><span style="font-family:courier;font-weight:bold">answer=10<br>read –p “pick -p "Enter a number between 1 and 10: “ guess" number<br>while test [ $guess –eq 10number -ne 5 ]<br>do <br> read –p “Try -p "Try again. Enter a number: “ guess" number<br> if [ $number -eq 5 ]<br> then<br> break<br> fi<br>done<br>echo “You are correct”</span><br><br>
===Using Startup Files=START-UP FILES====
'''Shell configuration (start-up) files ''' are '''scripts ''' that are run when you log in, log out, or start a new shell. <br>The start-up files can be used, for example, to '''set the prompt and screen display''', '''create local variables''', <br>or create temporary Linux commands ('''aliases''')
The '''/etc/profile''' file belongs to the root user and is the first start-up file that executes when you log in, regardless of shell.
User-specific config start-up files are in the user's home directory: <br><ul><li>'''~/.bash_profile''' runs when you log in .<br></li><li>The '''~/.bashrc''' runs when you start an interactive subBash shell.</li></ul><br>'''Logout Files''' There is a file that '''resets or restores the shell environment''' (including shut-down of programs running in the shell) when the user logs out of their shell. User-specific logout start-up files are in the user's home directory: '''~/.bash_logout'''<br><br> =INVESTIGATION 1: ADDITIONAL LOGIC STATEMENTS= <span style="color:red;">'''ATTENTION''': This online tutorial will be required to be completed by '''Friday in week 13 by midnight''' to obtain a grade of '''2%''' towards this course</span><br><br> In this investigation, you will learn additional control-flow statements<br>to allow your shell scripts to be even '''more adaptable'''. '''Perform the Following Steps:''' # '''Login''' to your matrix account.<br><br># Issue a command to '''confirm''' you are located in your home directory.<br><br># Issue a Linux command to create a directory called '''advanced'''<br><br># Issue a Linux command to <u>change</u> to the '''advanced''' directory.<br><br># Issue a Linux command to <u>confirm</u> you are located in the '''advanced''' directory.<br><br>In '''tutorial 10''', you learned how to use the '''if''' control-flow statement. You will now learn to use the '''if-else''' statement<br>to take two different actions based on if the condition tests either TRUE or FALSE.<br><br># Use a text editor like vi or nano to create the text file called '''if-4.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi if-4.bash</span>)<br><br># Enter the following lines in your shellscript:<br><span style="font-family:courier;font-weight:bold">#!/bin/bash<br>clear<br>read -p "Enter the first number: " num1<br>read -p "Enter the second number: " num2<br>if [ $num1 -gt $num2 ]<br>then<br> echo "The first number is greater than the second number."<br>elif [ $num1 -lt $num2 ]<br>then<br> echo "The first number is less than the second number."<br>else<br> echo "The first number is equal to the second number."<br>fi</span><br><br># Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':x''' followed by '''ENTER''').<br><br># Issue the following linux command to add execute permissions for your shell script:<br><span style="color:blue;font-weight:bold;font-family:courier;">chmod u+x if-4.bash</span><br><br># Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./if-4.bash</span><br><br>Try running the script several times with numbers different and equal to each other<br>to confirm that the shell script works correctly.<br><br>A <u>classic</u> shell script to demonstrate many different paths or actions to take depending of multiple testing<br>using an '''if-elif-else''' statement would be a '''mark to letter grade converter'''.<br><br># Use a text editor like vi or nano to create the text file called '''if-5.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi if-5.bash</span>)<br><br># Enter the following lines in your shell script:<br><span style="font-family:courier;font-weight:bold;">#!/bin/bash<br>clear<br>read -p "Enter a mark (0-100): " mark<br>if [ $mark -ge 80 ]<br>then<br> echo "You received an A grade."<br>elif [ $mark -ge 70 ]<br>then<br> echo "You received a B grade."<br>elif [ $mark -ge 60 ]<br>then<br> echo "You received a C grade."<br>elif [ $mark -ge 50 ]<br>then<br> echo "You received a D grade."<br>else<br> echo "You received an F grade."<br>fi</span><br><br># Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':x''' followed by '''ENTER''').<br><br># Issue the following linux command to add execute permissions for your shell script:<br><span style="color:blue;font-weight:bold;font-family:courier;">chmod u+x if-5.bash</span><br><br># Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./if-5.bash</span><br><br>What do you notice? Run several times to confirm that the shell script runs correctly for all mark (grade) categories.<br><br># Issue the following to run a checking script:<br><span style="color:blue;font-weight:bold;font-family:courier;">~uli101/week12-check-1</span><br><br># If you encounter errors, make corrections and '''re-run''' the checking script until you<br>receive a congratulations message, then you can proceed.<br><br> :In the next investigation, you will learn more about the '''for''' loop and learn how to use the '''while''' loop for '''error-checking'''.<br><br> =INVESTIGATION 2: ADDITIONAL LOOPING STATEMENTS =<br>In this investigation, you will learn more about the '''for''' loop<br>and learn how to use the '''while''' loop for '''error-checking'''. '''Perform the Following Steps:'''
<br>
In this sectioninvestigation, you will learn additional control-flow to use the '''exit''' and '''break''' statements to allow in your shell scripts to be more flexible.
'''THE EXIT STATEMENT'''
The '''exit''' statement is used to terminate a shell script.<br>This statement is very useful when combined with logic in a shell script to display an '''error message'''<br>if the command was '''improperly executed''' and '''terminate''' the running of the shell script.<br><br>The ''exit'' command can contain return a ''value'' to provide the '''exit status'''<br>of your shell script (i.e. TRUE or FALSE value).<br><br>
'''Perform the Following Steps:'''
# '''Login''' your Make certain that you are logged into matrix account.<br><br># Issue a command to '''confirm''' Confirm that you are currently located in your home directory.<br><br>In a previous tutorial, you learned how to using the '''if''' control-flow statement. You will now learn to use the 'advanced''if-else''' statement<br>to take two different actions based on if the condition tests either TRUE OR FALSEdirectory.<br><br># Use a text editor like vi or nano to create the text file called '''if-3exit.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi if-3exit.bash</span>)<br><br>If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.<br><br># Enter the following lines in your the '''exit.bash''' shell script:<br><span style="font-family:courier;font-weight:bold;">#!/bin/bash<br>clear<br>read -p "Enter the first number: " num1<br>read -p "Enter the second number: " num2<br>if [ $num1 # -gt $num2 ne 1 ]<br>then<br> echo "USAGE: $0 [arg]" > amp;2<br> echo "The first number is greater than the second number."exit 1<br>fi<br>else<br> echo "The first number argument is less than or equal to the second number.: $1"<br>fi</span><br><br># Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wxx''' followed by '''ENTER''').<br><br># Issue the following linux command to add '''Add execute permissions ''' for your this Bash shell script:<br><span style="color:blue;font-weight:bold;font-family:courier;">chmod u+x if-3.bash</span><br><br># Run your shell script by issuingIssue the following command (without arguments): <br><span style="color:blue;font-weight:bold;font-family:courier;">./if-3exit.bash</span><br><br>What do did you notice? Try <br><br>Since there are no arguments, the test within the running shell script returns FALSE,<br>then an '''error message''' with feedback of how to properly issue the shell script several times with numbers different an argument<br>and equal to each other tothen '''terminates''' the Bash shell script.<br><br>confirm Notice that the '''$0''' positional parameter displays the '''name''' of the currently running shell script works correctly.<br>It would be nice to have a separate result of in the numbers are equal to each otherUSAGE message. In order This is useful in case you decide to achieve this, you can use an '''if-elifchange''' the ''name''-else statementof the shell script at a later time.<br><br># Use a text editor like vi or nano The symbol '''>&2''' redirects '''standard output''' from the USAGE message<br>to create the text file called '''if-4standard error''' making like a <u>real</u> error message.bash<br>This "''neat redirection trick'' (eg" will NOT be considered for evaluation for this coverage. <br><br># Issue the following Linux command:<br><span style="color:blue;font-weight:bold;font-family:courier;">vi if-4.bashecho $?</span>)<br><br>If you are using What does this '''exit status''' from the nano text editor, refer to notes on text editing in a previous week in the course schedule.previously issued command indicate?<br><br># Enter Issue the following lines in your shell scriptcommand (with an argument):<br><span style="color:blue;font-weight:bold;font-family:courier;">#!/bin./exit.bashuli101<br/span>clear<br>read -p "Enter the first number: " num1<br>read -p "Enter the second number: " num2What did you notice this time?<br>if [ $num1 -gt $num2 ]<br>then# Issue the following Linux command:<br> <span style="color:blue; font-weight:bold; font-family:courier;">echo "The first number is greater than the second number."$?<br/span>elif [ $num1 -gt $num2 ]<br>then<br> echo "The first number is less than What does this '''exit status''' from the second number."previously issued command indicate?<br>else<br> echo "The first number is equal # Issue the following command (with two arguments and redirecting stderr to the second number."a file):<br>fi</spanstyle="color:blue;font-weight:bold;font-family:courier;"><br><br># Save your editing session and ./exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' followed by '''ENTER''')bash uli101 Linux 2> error.txt</span><br><br>NOTE: You should What did you notice in this control-flow statement differs from an if-else statement since if the first condition is FALSE, it is tested again, which can produce two different actions depending if the second test is TRUE or FALSE.time?<br><br># Issue the following linux Linux command to add execute permissions for your shell script:<br><span style="color:blue;font-weight:bold;font-family:courier;">chmod u+x if-4.bashecho $?</span><br><br># Run your shell script by issuingIssue the following Linux command to confirm that stderr was redirected to a file: <br><span style="color:blue;font-weight:bold;font-family:courier;">cat error./if-4.bashtxt</span><br><br>What do you notice? Try running the script several times with numbers different and equal to each other to confirm that the shell script works correctly. '''THE BREAK STATEMENT'''
The '''break''' statement is used to '''terminate''' a '''loop''' <u>without</u><br>
terminating the running shell script.
<br><br>
'''Perform the Following Steps:'''
=INVESTIGATION 4: USING START-UP FILES =<br>In this sectioninvestigation, you will learn how to ..'''customize''' your '''Bash Linux shell environment'''<br>by creating and testing a '''start-up''' file.
'''Perform the Following Steps:'''
# Issue a Linux command to change to your '''home''' directory.<br><br># Issue a Linux command to <u>confirm</u> you are located in the '''home''' directory.<br><br># Use the '''more''' command to view the contents of the '''default start-up''' file called '''/etc/profile''' <br><br>This file contains the '''default settings''' when you open your Bourne shell (eg. if issuing the command '''sh''').<br><br># Use the '''more''' command to view the contents of the start-up file called '''/etc/bashrc'''<br><br>This file contains the '''default settings''' when you '''open your Bash shell''' (eg. if issuing the command '''bash''').<br><br>Since we are using the '''Bash shell''' by default, let's create a '''customized Bash start-up file'''.<br>This startup file is located in your '''home''' directory using the name "'''.bash_profile'''"<br><br>Let's move your <span style="font-weight:bold;font-family:courier;">.bash_profile</span> file to prevent '''accidental overwrite'''.<br><br># Issue the following linux command:<br><span style="color:blue;font-weight:bold;font-family:courier;">mv ~/.bash_profile ~/.bash_profile.bk</span><br><br>If you experience an error message "''No such file or directory''",<br>just ignore this command since there is no '''~/.bash_profile''' file in your home directory.<br><br># Use a text editor like vi or nano to create the text file called '''~/.bash_profile''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi ~/.bash_profile</span>)<br><br>If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.<br><br># Enter the following lines in your shell script (the symbol "<span style="font-family:courier;font-weight:bold;">[</span>" is the open square bracket symbol):<br><span style="font-family:courier;font-weight:bold;">clear<br>echo -e -n "\e[0;34m"<br>echo "Last Time Logged in (for security):"<br>echo<br>lastlog -u $USER<br>echo<br>echo -e -n "\e[m"</span><br><br>'''NOTE:''' You will notice there is '''NO she-bang line''' since this is a '''start-up''' file.<br><br># Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':x''' followed by '''ENTER''').<br><br># You can test run the startup file without exiting and re-entering your Bash shell environment.<br>Issue the following:<br><span style="color:blue;font-weight:bold;font-family:courier;">. ~/.bash_profile</span><br><br>What do you notice?<br><br># '''Exit''' your current Bash shell session.<br><br># '''Login''' again to your matrix account.<br><br>Did you start-up file customize your Bash shell environment with colours?<br><br>'''NOTE:''' This is where you can make your Linux shell environment values '''persistent'''<br>(i.e. saved regardless of exit and login to your Bash Shell such as '''aliases''', '''umask''', etc.).<br><br># Issue the following linux command to '''restore''' your previous settings for your bashrc startup file:<br><span style="color:blue;font-weight:bold;font-family:courier;">mv ~/.bash_profile.bk ~/.bash_profile</span><br><br>If you experience an error message "''No such file or directory''", just ignore.<br><br># '''Exit''' your current Bash shell session.<br><br># '''Login''' again to your matrix account.<br><br>What did you notice this time?<br><br>
:* [https://wiki.cdot.senecacollege.ca/wiki/OPS245 OPS245: Basic Linux Server Administration]
:* [https://wiki.cdot.senecacollege.ca/wiki/OPS335 OPS335: Advanced Linux Server Administration]
= LINUX PRACTICE QUESTIONS =
simulate a quiz:
https://ictwiki.cdot.senecacollege.ca/~murray.saululi101/uli101files/uli101_week12_practice.docx
Your instructor may take-up these questions during class. It is up to the student to attend classes in order to obtain the answers to the following questions. Your instructor will NOT provide these answers in any other form (eg. e-mail, etc).
'''Review Questions:'''
# Write code for a Bash shell script that clears the screen, and then prompts the user for their age. If the age entered is less than 65, then display a message that the person is NOT eligible to retire. If the age is equal to 65, then display a message that the person just turned 65 and can retire. If the age is greater than 65, then display the message that the user is over 65 and why have they not have already retired already?<br><br># Add code to the script created in the <u>previous</u> question to force the user to enter only an '''integer''' to provide error-checking for this shell script.<br><br>#Write code for a Bash shell script that will prompt the user for a '''valid POSTAL CODE'''.<br>A valid postal code consists of the following format: '''x#x #x#'''<br>where '''x''' represents an upper or lowercase letter<br>and '''#''' represents a number from 0-9<br><br>Also VALID postal codes can consist of no spaces or one or more spaces in the format shown above.<br><br>If the user enters an '''INVALID postal code''', indicate an error and allow the user to enter the VALID postal code. When the user enters a VALID postal code, then clear the screen and display the VALID postal code.<br><br># Write code that works similar to the previous question, but have it read an input file called '''unchecked-postalcodes.txt''' and only save VALID postal codes to a file called:<br>'''valid-postalcodes.txt'''<br><br>Design your Bash Shell script to only run if the user enters TWO ARGUMENTS:<br>'''unchecked-postalcodes.txt''' and '''valid-postalcodes.txt'''<br><br>Otherwise, display an error message and immediately exit your Bash Shell script with a false exit value.<br><br># x What is the purpose of the '''/etc/profile''' startup file?<br><br># xWhat is the purpose of the '''/etc/bashrc''' startup file?<br><br># xWhat is the purpose of the '''~/.bashrc''' startup file?<br><br># xWhat is the purpose of the '''~/.bash_profile''' file?<br><br># xWhat is the purpose of the '''~/.bash_logout''' file?<br><br># xWrite <u>code</u> for the '''~/.bash_profile''' file below to clear the screen, welcome the user by their username, and display a list of all users currently logged into your Matrix server. Insert blank lines between each of those elements.<br><br># xWrite a command to <u>run</u> the recently created '''~/.bash_profile''' startup file from the previous question without exiting and re-logging into your Matrix account.<br><br> _________________________________________________________________________________ Author: Murray Saul License: LGPL version 3Link: https://www.gnu.org/licenses/lgpl.html _________________________________________________________________________________
[[Category:ULI101]]