Changes

Jump to: navigation, search

Tutorial12: Shell Scripting - Part 2

139 bytes added, 11:24, 27 October 2020
WHERE DO I GO FROM HERE?
===Main Objectives of this Practice Tutorial===
:* Use the Explain how to construct '''if-else''' and '''if-elif-else''' control flow statements.
:* Use alternative methods with Explain the purpose of '''forcommand substitution''' loop control flow statement.
:* Use Explain how to issue the '''for''' loop control flow statement using a list with '''command substitution''' with control-flow statements.
:* Configure Explain how to configure and use the '''.bashrc''' start-up file.<br><br>
===Tutorial Reference Material===
| style="padding-left:15px;" |Additional Control Flow Statements/ techniques
* [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://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html Using Command Substitution]
* [https://bash.cyberciti.biz/guide/While_loop while Loop]<br><br>
===Additional Logic Statements===
<br>
'''if-else statement:'''<br>[[Image:if-else.png|thumb|right|300px|Example of how an '''if-else''' statement works.<br>(Image licensed under [https://creativecommons.org/licenses/by-sa/3.0/ cc])]]'''if-else Statements'''
Unlike using only an ''if '' statement, an '''if-else ''' statement take '''two different sets of actions'''<br>based on the results of the test condition.<br><br>''How it Works:''<br>When the test condition returns a '''TRUE''' value, then the Linux Commands between<br>'''then''' and '''else''' statements are executed.<br>If the test returns a '''FALSE''' value, then the the Linux Commands between<br>the '''else''' and '''fi''' statements are executed.<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> &nbsp;&nbsp;&nbsp;echo “Less Than”<br>else<br>echo &nbsp;&nbsp;&nbsp;“Greater Than or Equal to”<br>fi</span><br><br>
'''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])]]'''if-elif-else Statements'''
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 new condition is tested''',<br>and action is taken if the result is '''TRUE''', then the Linux Commands between<br>'''then''' and '''else''' 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>
===Additional Loop Statements===
 
'''Command Substitution:'''
[[Image:for-command-substitution.png|thumb|right|300px|Example of how a '''for loop with command substitution''' works.]]
<i>'''Command substitution''' is a facility that allows a command<br>to be run and its output to be pasted back on the command line as arguments to another command.</i><br>Reference: https://en.wikipedia.org/wiki/Command_substitution<br><br>
''Usage:''
<span style="font-family:courier;font-weight:bold">file $(ls)<br>mail -s "message" $(cat email-list.txt) < message.txt<br><br>
'''Using the for Loop with Command Substitution'''
Let’s issue the for loop with a list using command substitution.<br>In the example below, we will use command substitution to issue the ls command and<br>have that output (filenames) become arguments for the for loop.<br><br>
<span style="font-family:courier;font-weight:bold;">for x in $(ls)<br>do<br> &nbsp;&nbsp;&nbsp;echo “The item is: $x”<br>done</span><br><br>
'''While Loops:'''
[[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])]]
[[Image:while-loop.png|thumb|right|170px|Example of how a '''while''' loop works.]]'''Using the while Loop Statement''' The '''while''' loop is useful to loop based on the result from a test condition or command result.<br>This type of loop is very useful for '''error-checking'''.<br><br>''<i>How it Works:''</i><br>The condition/expression is evaluated, and if the condition/expression is '''TRUE''',<br>the code within … the block is executed. ''
This repeats until the condition/expression becomes '''FALSE'''.<br>Reference: https://en.wikipedia.org/wiki/While_loop<br><br>
# '''Login''' to your matrix account.<br><br>
# Issue a command to '''confirm''' you are located in your home directory.<br><br>In a previous tutorial, you learned how to using 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 or FALSE.<br><br>
# Use a text editor like vi or nano to create the text file called '''if-3.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi if-3.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 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 ]<br>then<br>&nbsp;&nbsp;&nbsp;echo "The first number is greater than the second number."<br>else<br>&nbsp;&nbsp;&nbsp;echo "The first number is less than or 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 ''':wx''' 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-3.bash</span><br><br>
# Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./if-3.bash</span><br><br>What do you notice? Try running the script several times with numbers different and equal to each other to<br>confirm that the shell script works correctly.<br><br>It would be nice to have a separate result of the numbers are equal to each other.<br>In order to achieve this, you can use an '''if-elif-else'''-else statement.<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>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:<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>&nbsp;&nbsp;&nbsp;echo "The first number is greater than the second number."<br>elif [ $num1 -lt $num2 ]<br>then<br>&nbsp;&nbsp;&nbsp;echo "The first number is less than the second number."<br>else<br>&nbsp;&nbsp;&nbsp;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 ''':wx''' followed by '''ENTER''').<br><br>NOTE: You should 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.<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>What do you notice? 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>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:<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>&nbsp;&nbsp;&nbsp;echo "You receive an A grade."<br>elif [ $mark -ge 70 ]<br>then<br>&nbsp;&nbsp;&nbsp;echo "The receive a B grade."<br>elif [ $mark -ge 60 ]<br>then<br>&nbsp;&nbsp;&nbsp;echo "The receive a C grade."<br>elif [ $mark -ge 50 ]<br>then<br>&nbsp;&nbsp;&nbsp;echo "The receive a D grade."<br>else<br>&nbsp;&nbsp;&nbsp;echo "You receive an F grade."<br>fi</span><br><br>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' 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>
: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 =
In this section, you will learn more about the for loop and learn how to use the '''while ''' loop for '''error-checking'''
'''Perform the Following Steps:'''
# Use the '''more''' command to view the contents of the text file called '''for-1.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">more for-1.bash</span>)<br><br>As you should have noticed from ''tutorial 10'' that the '''for''' loop can use a '''list'''.<br>You can also use the for loop with positional parameters stored as arguments from an executed shell script.<br>We will revisit this now.<br><br># Use the more command to view the text file called '''for-2.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">more for-2.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># Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./for-2.bash 10 9 8 7 6 5 4 3 2 1</span><br><br>You should notice the script looped for each argument following the shell script.<br><br>You can also use the for loop with a list using '''command substitution''' - this is an effective technique to loop within a shell script.<br><br># FirstBefore creating a new shell script, you need to let's learn how to use command substitution from the Bash Shell to store arguments as positional parametersand use them for practice.<br>Issue the following linux command to set positional parameters in your current shell:<br><span style="color:blue;font-weight:bold;font-family:courier;">set apples oranges bananas pears</span><br><br>
# Issue the following linux command:<br><span style="color:blue;font-weight:bold;font-family:courier;">echo $#</span><br><br>What do you notice?<br><br>
# Issue the following linux command:<br><span style="color:blue;font-weight:bold;font-family:courier;">echo $*</span><br><br>What do you notice?<br><br>These positional parameters could be used with a for loop. To simplify things, let's create another shell script that uses '''command substitution ''' and a '''for ''' loop.<br><br>
# Use a text editor like vi or nano to create the text file called '''for-2.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi for-3.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 shell script:<br><span style="font-family:courier;font-weight:bold;">#!/bin/bash<br>clear<br>set 10 9 8 7 6 5 4 3 2 1<br>for x<br>do<br>&nbsp;&nbsp;&nbsp;echo $x<br>done<br>echo "blast-off!"</span><br><br>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' 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 for-3.bash</span><br><br>
# Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./for-3.bash</span><br><br>What do you notice? How does the result differ from the shell script called for-2.bash. Why?<br><br>Let's create another shell script to '''run a loop for each file ''' that is contained in your current directory using '''command substitution'''.<br><br>
# Use a text editor like vi or nano to create the text file called '''for-4.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi for-4.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 shell script:<br><span style="font-family:courier;font-weight:bold;">#!/bin/bash<br>clear<br>set $(ls)<br>echo Here are files in my current directory:"<br>echo<br>for x<br>do<br>&nbsp;&nbsp;&nbsp;echo " &nbsp;&nbsp;&nbsp;$x"<br>done</span><br><br>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' 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 for-4.bash</span><br><br>
# Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./for-4.bash</span><br><br>What do you notice?<br><br>We can save reduce a line in our shell script by using '''command substitution ''' in the for loop instead of using a listthe '''set''' command. <br>Let's demonstration demonstrate this in another shell script.<br><br>
# Use a text editor like vi or nano to create the text file called '''for-5.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi for-5.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 shell script:<br><span style="font-family:courier;font-weight:bold;">#!/bin/bash<br>clear<br>echo Here are files in my current directory:"<br>echo<br>for x in $(ls)<br>do<br>&nbsp;&nbsp;&nbsp;echo " &nbsp;&nbsp;&nbsp;$x"<br>done<br></span>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' 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 for-5.bash</span><br><br>
# Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./for-5.bash</span><br><br>What do you notice? Does the output for this shell script differ than '''for-4.bash'''? Why?<br><br>The last thing in this section is to introduce you to '''error-checking'''.<br><br>
# Use the '''more''' command to view the text file called '''if-5.bash''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">more if-5.bash</span>)<br><br>Take a few moments to re-familiarize yourself with this shell script<br><br>
# Run your shell script by issuing: <span style="color:blue;font-weight:bold;font-family:courier;">./if-5.bash </span><br><br>When prompted, enter a letter instead of a number. What happens?<br><br>Let's edit the '''if-5.bash ''' shell script to perform '''error-checking ''' to <u>force </u> the user to enter a numeric value between 0 and 100.<br><br>'''NOTE:''' The '''while''' statement can be used with the '''test''' command (or a simple linux command or a linux pipeline command) for error checking. In our case, we will use a pipeline command with extended regular expressions. In order to loop while the result is TRUE (not FALSE), you can use the negation symbol (!) to set the test condition to the opposite.<br><br>
# Use a text editor like vi or nano to edit 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>If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.<br><br>
# Add the following lines in your shell script <u>AFTER</u> the read statement to prompt the user for a mark:<br><span style="font-family:courier;font-weight:bold;"><br>while ! echo $mark | egrep "^[0-9]{1,}$" > /dev/null 2> /dev/null<br>do<br> &nbsp;&nbsp;&nbsp;read -p "Not a valid number. Enter a mark (0-100): " mark<br>done</span><br><br>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' followed by '''ENTER''').<br><br>
# Run your shell script by issuing:<br><span style="color:blue;font-weight:bold;font-family:courier;">./if-5.bash</span><br><br>
# When prompted, enter a letter instead of a number. What happens?<br>Does the shell script allow you to enter an invalid grade like 200 or -6?<br><br>Let's add an additional error-checking loop to force the user to enter a number between 0 and 100.<br><br>
# Use a text editor like vi or nano to edit 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>
# Add the following lines in your shell script <u>AFTER</u> the PREVIOUSLY ADDED error-checking code block to force the user to enter a valid number:<br><span style="font-family:courier;font-weight:bold;"><br>while [ $mark -lt 0 ] || [ $mark -gt 100 ]<br>do<br> &nbsp;&nbsp;&nbsp;read -p "Invalid number range. Enter a mark (0-100): " mark<br>done</span><br><br>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' followed by '''ENTER''').<br><br>
# Run your shell script by issuing:<br><span style="color:blue;font-weight:bold;font-family:courier;">./if-5.bash</span><br><br>
# When prompted, enter a letter instead of a number. What happens?<br>Does the shell script allow you to enter an invalid grade like 200 or -6?<br><br>
:In the next investigation, you will learn to create and test-out the '''~/.bashrc''' start-up files file to customize your Bash shell.
=INVESTIGATION 3: USING STARTUP START-UP FILES =
In this section, you will learn how to '''customize ''' your '''Bash Linux shell environment''' by creating and testing a startup start-up file.
'''Perform the Following Steps:'''
# Use the '''more''' command to view the contents of the start-up file called '''/etc/profile''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">more /etc/profile</span>)<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''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">more /etc/bashrc</span>)<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 "'''.bashrc'''"<br><br>
# Let's move your .bashrc file to prevent accidental overwrite. Issue the following linux command:<br><span style="color:blue;font-weight:bold;font-family:courier;">mv ~/.bashrc ~.bashrc.bk</span><br><br>If you experience an error message "''No such file or directory''", just ignore since there is no startup file to backup.<br><br>
# Use a text editor like vi or nano to create the text file called '''~/.bashrc''' (eg. <span style="color:blue;font-weight:bold;font-family:courier;">vi ~/.bashrc</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>
# Save your editing session and exit the text editor (eg. with vi: press '''ESC''', then type ''':wx''' 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;">. ~/.bashrc</span><br><br>What do you notice?<br><br>
# '''Login''' again to your matrix account.<br><br>Did you start-up file customize your Bash shell environment with colours?<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 ~/.bashrc.bk ~/.bashrc</span><br><br>If you experience an error message "''No such file or directory''", just ignore.<br><br>
 
# After you complete the Review Questions sections to get additional practice, then work on your '''online assignment 3,'''<br>'''sections 4 to 6''' labelled: '''More Scripting (add)''', '''Yet More Scripting (oldfiles)''', and '''sed And awk'''<br><br>
= WORKING EFFECTIVELY IN THE LINUX ENVIRONMENT WHERE DO I GO FROM HERE? =
I hope this series of tutorials have been helpful in teaching you basic Linux OS skills.
In order to get efficient in working in the Linux environment requires '''practice''' and '''applying''' what you have learned to administering Linux operating systems including '''users''', '''applications''', '''network services''' and '''network security'''.
Although you are '''NOT''' required to perform advanced '''Linux administration ''' for this course, there are useful course notes and '''tutorials ''' for advanced Linux server administration that have been created for the Networking / Computer Support Specialist stream:
Take care and good luck in your future endeavours,
<span style="font-size:1.3em; font-family:cursive">Murray Saul</span>
= LINUX PRACTICE QUESTIONS =
13,420
edits

Navigation menu