Difference between revisions of "Tutorial 12 - Shell Scripting - Part 2"

From CDOT Wiki
Jump to: navigation, search
(INVESTIGATION 1: ADDITIONAL LOGIC STATEMENTS)
Line 132: Line 132:
  
 
= INVESTIGATION 1: ADDITIONAL LOGIC STATEMENTS =
 
= INVESTIGATION 1: ADDITIONAL LOGIC STATEMENTS =
 +
<span style="color:red;">'''ATTENTION''': The due date for successfully completing this tutorial (i.e. tutorial 12) is by Friday, December 15 @ 11:59 PM (Week 14).</span><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 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 ''':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>&nbsp;&nbsp;&nbsp;echo "You received an A grade."<br>elif [ $mark -ge 70 ]<br>then<br>&nbsp;&nbsp;&nbsp;echo "You received a B grade."<br>elif [ $mark -ge 60 ]<br>then<br>&nbsp;&nbsp;&nbsp;echo "You received a C grade."<br>elif [ $mark -ge 50 ]<br>then<br>&nbsp;&nbsp;&nbsp;echo "You received a D grade."<br>else<br>&nbsp;&nbsp;&nbsp;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;">~osl640/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 =
 
= INVESTIGATION 2: ADDITIONAL LOOPING STATEMENTS =

Revision as of 14:06, 14 November 2021

Content under development

ADDITIONAL SHELL SCRIPTING

Main Objectives of this Practice Tutorial

  • Use the if-elif-else control flow statement in a shell script.
  • Use the for loop control using a list with command substitution.
  • Use the while loop in a shell script.
  • Use the exit and break statements in a shell script.
  • Explain how to configure and use a .bashrc start-up file.


Tutorial Reference Material

Course Notes
Linux Command/Shortcut Reference
YouTube Videos
Course Notes:


Control Flow Statements

Additional Statements

Startup Files


Brauer Instructional Videos:

KEY CONCEPTS

IF-ELIF-ELSE STATEMENT

Example of how an if-elif-else statement works.
(Image licensed under 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.

How it Works:
If the test condition returns a TRUE value, then the Linux Commands between
then and else statements are executed.

If the test returns a FALSE value, then a new condition is tested again,
and action is taken if the result is TRUE, then the Linux Commands between
then and else statements are executed. Additional elif statements can be used if additional conditional testing is required . Eventually, an action will be taken
when the final test condition is FALSE.

Example:

num1=5
num2=10
if test $num1 –lt $num2
then
   echo “Less Than”
elif test $num1 –gt $num2
then
   echo “Greater Than”
else    echo “Equal to”
fi


FOR LOOP USING COMMAND SUBSTITUTION

Let’s issue the for loop with a list using command substitution.
In the example below, we will use command substitution to issue the ls command and
have that output (filenames) become arguments for the for loop.

Example:

for x in $(ls)
do
   echo “The item is: $x”
done


WHILE LOOP

Example of how a while loop works.
(Image licensed under cc)

The while loop is useful to loop based on the result from a test condition or command result.
This type of loop is very useful for error-checking.

How it Works:
The condition/expression is evaluated, and if the condition/expression is TRUE,
the code within … the block is executed.
This repeats until the condition/expression becomes FALSE.
Reference: https://en.wikipedia.org/wiki/While_loop

Example 1:

answer=10
read –p “pick a number between 1 and 10: “ guess
while test $guess –eq 10
do    read –p “Try again: “ guess
done
echo “You are correct”



Example 2:

value=1
while [ $value -le 5 ]
do
  echo "$value"
  ((value=value+1)) # could also use ((value++))
done
1
2
3
4
5


EXIT & BREAK STATEMENTS


exit Statement

The exit statement is used to terminate a shell script.
This statement is very useful when combined with logic in a shell script.
The exit command can contain an argument to provide the exit status of your shell script.

Example:

if [ $# -ne 1 ]
then
  echo "USAGE: $0 [arg]"
  exit 1
fi

break Statement

The break statement is used to terminate a loop.
Although the loop terminates, the shell script will continue running.

Example:
read -p "Enter a number: " number
while [ $number -ne 5 ]
do
   read -p "Try again. Enter a number: " number
   if [ $number -eq 5 ]
   then
     break
   fi
done


START-UP FILES

Shell configuration (start-up) files are scripts that are run when you log in, log out, or start a new shell.
The start-up files can be used, for example, to set the prompt and screen display, create local variables,
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:

  • ~/.bash_profile runs when you log in.
  • The ~/.bashrc runs when you start an interactive Bash shell.


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


INVESTIGATION 1: ADDITIONAL LOGIC STATEMENTS

ATTENTION: The due date for successfully completing this tutorial (i.e. tutorial 12) is by Friday, December 15 @ 11:59 PM (Week 14).

In this investigation, you will learn additional control-flow statements
to allow your shell scripts to be even more adaptable.


Perform the Following Steps:

  1. Login to your matrix account.

  2. Issue a command to confirm you are located in your home directory.

  3. Issue a Linux command to create a directory called advanced

  4. Issue a Linux command to change to the advanced directory.

  5. Issue a Linux command to confirm you are located in the advanced directory.

    In tutorial 10, you learned how to use the if control-flow statement. You will now learn to use the if-else statement
    to take two different actions based on if the condition tests either TRUE or FALSE.

  6. Use a text editor like vi or nano to create the text file called if-4.bash (eg. vi if-4.bash)

  7. Enter the following lines in your shell script:
    #!/bin/bash
    clear
    read -p "Enter the first number: " num1
    read -p "Enter the second number: " num2
    if [ $num1 -gt $num2 ]
    then
       echo "The first number is greater than the second number."
    elif [ $num1 -lt $num2 ]
    then
       echo "The first number is less than the second number."
    else
       echo "The first number is equal to the second number."
    fi


  8. Save your editing session and exit the text editor (eg. with vi: press ESC, then type :x followed by ENTER).

  9. Issue the following linux command to add execute permissions for your shell script:
    chmod u+x if-4.bash

  10. Run your shell script by issuing: ./if-4.bash

    Try running the script several times with numbers different and equal to each other
    to confirm that the shell script works correctly.

    A classic shell script to demonstrate many different paths or actions to take depending of multiple testing
    using an if-elif-else statement would be a mark to letter grade converter.

  11. Use a text editor like vi or nano to create the text file called if-5.bash (eg. vi if-5.bash)

  12. Enter the following lines in your shell script:
    #!/bin/bash
    clear
    read -p "Enter a mark (0-100): " mark
    if [ $mark -ge 80 ]
    then
       echo "You received an A grade."
    elif [ $mark -ge 70 ]
    then
       echo "You received a B grade."
    elif [ $mark -ge 60 ]
    then
       echo "You received a C grade."
    elif [ $mark -ge 50 ]
    then
       echo "You received a D grade."
    else
       echo "You received an F grade."
    fi


  13. Save your editing session and exit the text editor (eg. with vi: press ESC, then type :x followed by ENTER).

  14. Issue the following linux command to add execute permissions for your shell script:
    chmod u+x if-5.bash

  15. Run your shell script by issuing: ./if-5.bash

    What do you notice? Run several times to confirm that the shell script runs correctly for all mark (grade) categories.

  16. Issue the following to run a checking script:
    ~osl640/week12-check-1

  17. If you encounter errors, make corrections and re-run the checking script until you
    receive a congratulations message, then you can proceed.

In the next investigation, you will learn more about the for loop and learn how to use the while loop for error-checking.

INVESTIGATION 2: ADDITIONAL LOOPING STATEMENTS

INVESTIGATION 3: USING STARTUP FILES

LINUX PRACTICE QUESTIONS