Tutorial10: Shell Scripting - Part 1

From CDOT Wiki
Revision as of 17:26, 17 February 2021 by Msaul (talk | contribs) (INVESTIGATION 2: USING VARIABLES IN SHELL SCRIPTS)
Jump to: navigation, search

INTRODUCTION TO SHELL SCRIPTING


Main Objectives of this Practice Tutorial

  • Explain the purpose of the she-bang line contained at the top of a shell script.
  • List rules for naming a Bash script file.
  • Explain how to set permissions and how to execute a shell script.
  • Explain the purpose of environment and user-defined variables.
  • Explain the purpose of control flow statements.
  • Explain the purpose of the test command.
  • Explain the purpose and usage of the if logic statement and the for loop statement

Tutorial Reference Material

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


Shell Scripting

Variables

Commands

Control Flow Statements Instructional Videos:

KEY CONCEPTS

A shell script is a computer program designed to be run by the Unix shell, a command-line interpreter.
The various dialects of shell scripts are considered to be scripting languages.

Reference: https://en.wikipedia.org/wiki/Shell_script

Creating & Executing Shell Scripts

An IPSO Diagram (INPUT, PROCESSING, STORAGE, OUTPUT) can be used to map-out and then list the sequence of steps to assist when coding your shell script.

It is recommended to plan out on a piece of paper the purpose of the shell script.
You can do this by creating a simple IPSO diagram (stands for INPUT, PROCESSING, STORAGE, OUTPUT).

First, list the INPUTS into the script (eg. prompting user for data, reading data from file, etc), then listing the expected OUTPUTS from the script. You can then list the steps to process the INPUT to provide the OUTPUT (including file storage).

Once you have planned your shell script by listing the sequence of steps (i.e. PROCESSING) in your script, you need to create a file (using a text editor) that will contain your Linux commands.

NOTE: Avoid using filenames of already existing Linux Commands to avoid confusion.
Using shell script filenames that include the file extension of the shell that the script will run within is recommended.

Using a Shebang Line

The shebang line must appear on the first line and at the beginning of the shell script.
If you are learning Bash scripting by reading other people’s code you might have noticed
that the first line in the scripts starts with the #! characters and the path to the Bash interpreter.

This sequence of characters (#!) is called shebang and is used to tell the operating system
which interpreter to use to parse the rest of the file.
Reference: https://linuxize.com/post/bash-shebang/

The shebang line must appear on the first line and at the beginning of the shell script,
otherwise, it will be treated as a regular comment and ignored.

Setting Permissions & Running a Shell Script

To run your shell script by name, you need to assign execute permissions for the user.
To run the shell script, you can execute the shell script using a relative, absolute, or relative-to-home pathname

Example:

chmod u+x myscript.bash
./myscript.bash
/home/username/myscript.bash
~/myscript.bash

Using Variables in Shell Scripts

Definition

Variables are used to store information to be referenced and manipulated in a computer program.
They also provide a way of labeling data with a descriptive name, so our programs can be understood
more clearly by the reader and ourselves.

Reference: https://launchschool.com/books/ruby/read/variables


Environment Variables

Examples of using Environment and User Defined variables.
Shell environment variables shape the working environment whenever you are logged in Common shell. Some of these variables are displayed via Linux commands in the diagram displayed on the right-side.
(you can issue the pipeline command set | more to view all variables)

Placing a dollar sign ($) prior to the variable name will cause the variable to expand to the value contained in the variable.


User Defined Variables

User-defined variables are variables which can be created by the user and exist in the session. This means that no one can access user-defined variables that have been set by another user,
and when the session is closed these variables expire.

Reference: https://mariadb.com/kb/en/user-defined-variables/

Data can be stored and removed within a variable using an equal sign.
The read command can be used to prompt the user to enter data into a variable.
Refer to the diagram on the right-side to see how user-defined variables are assigned data.

Positional Parameters and Special Parameters

Examples of using positional and special parameters.
A positional parameter is a variable within a shell program; its value is set from an argument specified on the command line that invokes the program.

Positional parameters are numbered and their values are accessed by using a preceding "$" (eg. $1$2$3, etc.). The positional parameter $0 refers to either the name of shell where command was issued, or name of shell script being executed. If using positional parameters greater than 9, then you need to include number within braces.
Examples: echo ${10}, ls ${23}

The shift command can be used with positional parameters to shift positional parameters
to the left by one or more positions.

There are a couple of ways to assign values as positional parameters:

  • Use the set command with the values as argument after the set command
  • Run a shell script containing arguments


There are a group of special parameters that can be used for shell scripting.
A few of these special parameters and their purpose are displayed below:
$* , “$*” , "$@" , $# , $?

Refer to the diagram to the right for examples using positional and special parameters.

Using Control Flow Statements in Shell Scripts

Examples of simple comparisons using the test command.
Examples of using additional comparisons using the test command.

Control Flow Statements are used to make your shell scripts more flexible and can adapt to changing situations.

The special parameter $? Is used to determine the exit status of the previously issued Linux command. The exit status will either display a zero (representing TRUE) or a non-zero number (representing FALSE). The test command can be used with control flow statements to control the sequence of a shell script.

You CANNOT use the > or < symbols when using the test command since these are redirection symbols. Instead, you need to use options when performing numerical comparisons. Refer to the table below for test options and their purposes.

There are other comparison options that can be used with the test command such as testing to see if a regular file or directory pathname exists, or if the regular file pathname is –non-empty.

Refer to diagrams to the right involving some of the options used with the test command. Refer to the test man pages for a full list of options for the test command.

Logic Statements

A logic statement is used to determine which Linux commands to be executed based
on the result of a condition (i.e. TRUE (zero value) or FALSE (non-zero value)).

Example of using the if logic control-flow statement.
Example of using the for looping control-flow statement.

There are several logic statements, but we will just concentrate on the if statement.

if test condition
  then
     command(s) 
fi

Refer to the diagram immediately to the right for using the if logic statement with the test command.

Loop Statements

A loop statement is a series of steps or sequence of statements executed repeatedly zero or more times satisfying the given condition is satisfied.
Reference: https://www.chegg.com/homework-help/definitions/loop-statement-3

There are several loops, but we will look at the for loop using a list.

for item in list 
do
    command(s) 
done

Refer to the diagram above and to the extreme right side for an example using the for loop with a list.

INVESTIGATION 1: CREATING A SHELL SCRIPT


In this section, you will learn how to create and run a simple Bash Shell script.


Perform the Following Steps:

  1. Login to your matrix account.

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

    We want to create a Bash Shell script to welcome the user by their username.
    Let's first provide some useful tips in terms of selecting an appropriate name for the shell script.

  3. Issue the following linux command to check if your intended shell script name
    is already exists to be run automatically from the Bash shell:
    which hello

    You should notice that there is no output and therefore, this shell script name can be used.
    On the other hand, if you wanted to create a file called sed, then the which sed command
    would indicate it is already being used by the shell and that sed wouldn't be an appropriate shell script name to use.

  4. Use a text editor like vi or nano to create the text file called hello

    If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.

  5. Enter the following two lines in your shell script, replacing "your-username" with your actual name:
    echo
    echo "Hello $USER"
    echo


    NOTE: The variable called USER is an environment variable that contains the current user's login name.
    In this way if you wanted to share your shell script with other users, when they run the shell script
    it will greet by their username. Using environment variables makes your shell script to be more "usable" by others.

  6. Save your editing session and exit the text editor.

    Instead of issuing the bash command followed by your shell script pathname as an argument,
    let's simply run it by its filename. This is the most common method of running shell scripts.

  7. Issue the following linux command to run your shell script in your current directory:
    ./hello

    You should notice an error indicating you don't have permissions to run the file.
    You need to first add execute permissions prior to running the shell script.

  8. Issue the following linux command to add execute permissions for your shell script:
    chmod u+x hello

  9. Re-run your shell script: ./hello

    Did you shell script run?

  10. Issue the following Linux command to run a checking script:
    bash /home/murray.saul/scripts/week10-check-1

  11. 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 to create and run shell scripts that
use variables, positional and special parameters. You will also learn
how to add a she-bang line at the top of a shell script to force it to run in a specified shell.

INVESTIGATION 2: USING VARIABLES IN SHELL SCRIPTS

In this section, you will learn how to use variables, positional and special parameters to assist you in creating adaptable shell scripts.


Perform the Following Steps:

  1. Confirm that you are located in your home directory in your Matrix account.

  2. Use a text editor to edit the shell script called hello

  3. Add the following line to the bottom of the file:
    ps -o cmd= -p $$|cut -d" " -f1

    NOTE: This command displays the name of the shell that the shell script
    is running within.

  4. Save your editing changes and exit your text editor.

  5. Issue the following linux command to run this shell script with the Bourne Shell (i.e. sh):
    sh hello

  6. Issue the following linux command to confirm you are in the Bourne Shell:
    echo $0

    You should see the output of the command that you are located in shows sh (i.e. the Bourne Shell).

  7. While in the Bourne Shell, run your shell script: ./hello

    What shell does the shell script indicate is running?
    You should notice that this script is being run in the Bourne shell.

    Although your shell script should work, it is recommended to force your shell script to run in a specific shell.
    This helps prevent your shell script encountering errors when run in the incorrect shell
    (i.e. syntax not recognized in a specific shell).

  8. Edit your hello shell script using a text editor.

  9. Insert the following line at the beginning of the first line of your hello file:
    #!/bin/bash

    This is referred to as a she-bang line. It forces the script to be run in the Bash Shell.
    When your Bash Shell script finishes execution, you are returned to your current shell that you are using
    (which in our case in Matrix, is still the Bash shell).

  10. Save your editing changes and exit your text editor.

  11. It is a good idea to rename your shell script to include an extension to indicate that the file is a Bash Shell script file.
    Issue the following linux command to rename your shell script file:
    mv hello hello.bash

  12. Run your renamed shell script for confirmation by issuing:
    ./hello.bash

  13. Enter the following linux command to return to your Bash shell: exit

  14. Issue the following Linux command to confirm you have returned to the Bash shell: echo $SHELL

    Let's use some ENVIRONMENT variables in our Bash Shell script.

  15. Use a text editor to edit the shell script called hello.bash

  16. Add the following lines to the bottom of the file:
    echo
    echo "The current directory location is: $PWD"
    echo "The current user home directory is: $HOME
    echo


  17. Save your editing changes and exit your text editor.

  18. Run your renamed shell script for confirmation by issuing:
    ./hello.bash

    Take time to view the output and the values of the environment variables.

  19. Issue the following linux command to add your current directory to the PATH environment variable:
    PATH=$PATH:.

  20. Issue the following linux command to confirm that the current directory "." has been added to the PATH environment variable:
    echo $PATH

  21. Issue the following to run your Bash shell script just by name:
    hello.bash

    Did your Bash shell script run?

  22. Exit your Matrix session, and log back into your Matrix session.

  23. Re-run the hello.bash shell script by just using the name.

    What did you notice?

    The setting of the PATH environment variable only worked in the current session only.
    If you exit the current Matrix session, then the recently changed settings for environment variables will be lost.
    You will in a future tutorial how to set environment variables in start-up files.

    ATTENTION: Students will get FRUSTRATED when performing their assignment 3 when their Bash shell scripts have errors. One major cause is the the OUTPUT of their Bash shell script when run does not EXACTLY match the required output for the correct Bash shell script. This requires that you CAREFULLY read the requirements of your Bash shell script and create it to the EXACT specifications.

  24. Issue the following Linux command to run a checking script:
    bash /home/murray.saul/scripts/week10-check-2 | more

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

    Let's create a Bash shell script that contain user-created variables.

  26. Use a text editor to create a Bash shell script called user-variables.bash

  27. Add the following lines to the beginning of this file:
    #!/bin/bash
    age=25
    readonly age
    read -p "Enter your Full Name" name
    read -p "Enter your age (in years): " age
    echo "Hello $name - You are $age years old"


  28. Save your editing changes and exit your text editor.

  29. Issue the chmod command to add execute permissions for the user for the user-variables.bash file.

  30. Issue the following to run the user-variables.bash Bash shell script:
    ./user-variables.bash

    What do you notice when you try to change the age variable? Why?

  31. Use a text editor to create a file called parameters.bash

  32. Add the following lines to the beginning of this file:
    #!/bin/bash
    echo \$0: $0
    echo \$2: $2
    echo \$3: $3

    echo \$#: $#
    echo \$*: $*

    shift 2
    echo \$#: $#
    echo \$*: $*


  33. Save your editing changes and exit your text editor.

    Notice how the quoting character "\" is used to display positional parameters like "$2"
    as opposed to the value stored in the second positional parameter.

  34. Issue the chmod command to add execute permissions for the user for the parameters.bash file.

  35. Issue the following to run the user-variables.bash Bash shell script:
    ./parameters.bash

    What happened?

    The values for the parameters may not be displayed properly since you did NOT provide any arguments when running the shell script.

  36. Issue the following to run the user-variables.bash Bash shell script with arguments:
    ./parameters.bash 1 2 3 4 5 6 7 8

    Take some time to view the results and how the parameters are changed when using the shift command. What do you notice?


In the next investigation, you will use control-flow statements to allow your shell scripts to perform differently under different situations.

INVESTIGATION 3: USING CONTROL FLOW STATEMENTS

In this section, you will learn how to use control-flow statements to make your shell script behave differently under different situation.


Perform the Following Steps:

Before learning about logic and loop control-flow statements, you need to first learn about issuing test conditions using the test command.

  1. Confirm that you are located in your home directory in your Matrix account.

  2. Issue the following linux commands at the Bash shell prompt to assign values to several variables:
    course="ULI101"
    number1=5
    number2=10


  3. Issue the following linux command to test a condition:
    test $course = "ULI101"

    The $? variable is used to store an exit status of the previously command issued (including the test command). If the status is zero, then it indicates a TRUE value and if the status is non-zero, then it indicates a FALSE value.

  4. Issue the following linux command to view the status of the previously-issued test command:
    echo $?

    Based on its value, is the result TRUE or FALSE?

  5. Issue the following linux command to test another condition:
    test $course = "uli101"

  6. Issue the following linux command to view the status of the previously-issued test command:
    echo $?

    The value is non-zero (FALSE) since UPPERCASE characters are different than lowercase characters.

  7. Issue the following linux command to test another condition:
    test $course != "uli101"

  8. Issue a linux command to display the value of $?. What is the result? Why?

  9. Issue the following linux command to test a condition involving numbers:
    test $number1 > $number2

  10. Issue a linux command to display the value of $?. NOTE: You will notice that something is wrong.
    The exit status $? shows a zero (TRUE) value, but the number 5 is definitely NOT greater than 10.
    The problem is that the symbols < and > are interpreted as REDIRECTION symbols!

  11. To prove this, issue the following linux command :
    ls 10

    You should notice a file called "10". The incorrectly issued test command used redirect to create an empty file instead,
    which indeed succeeded just giving a TRUE value!

    To prevent problems when issuing the test command when comparing numbers, you can use the following options:
    -lt (<), -le (<=), -gt (>), -ge (>=;), -eq (=), -ne (!=)

  12. Issue the correct linux command to properly test both values:
    test $number1 -gt $number2

  13. Issue a linux command to display the value of $?.
    You should notice that the exit status value is now FALSE which is the correct result.

  14. The test command can be abbreviated by the square brackets [ ] which contain the test condition within the square brackets. You need to have spaces between the brackets and the test condition; otherwise, you will get a test error.

  15. To generate a test error, copy and paste the following test command:
    [$number1 -gt $number2]

    You should notice an test error message.

  16. Copy and paste the following (correct) test command:
    [ $number1 -gt $number2 ]

    Issue a command to view the value of the exit status of the previously issued test command. You should notice that is works properly.

    Let's now learn about control-flow statements:

    Logic statements are used to create different paths or directions based on the result of testing conditions. In this tutorial, we will only focus on the if logic statement.

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

    If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.

  18. Enter the following lines in your shell script:
    #!/bin/bash
    clear
    num1=5
    num2=10
    if [ $num1 -gt $num2 ]
    then
       echo "Greater Than"
    fi


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

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

  21. Run your shell script by issuing: ./if-1.bash

    Confirm that the output indicated a correct result.

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

    If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.

  23. 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."
    fi


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

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

  26. Run your shell script by issuing: ./if-2.bash

    Confirm that the output indicated a correct result.

    What happens when you enter a first number that is less than or equal to the second number? We will learn about if-else and if-elif-else statements in a couple of weeks.

    Loop statements are used to provide repetition in a shell script. In this tutorial, we will only focus on the for loop statement.

  27. Use a text editor like vi or nano to create the text file called for-1.bash (eg. vi for-1.bash)

    If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.

  28. Enter the following lines in your shell script:
    #!/bin/bash
    echo
    for x in 5 4 3 2 1
    do
       echo $x
    done
    echo "blast-off!"
    echo


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

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

  31. Run your shell script by issuing: ./for-1.bash

  32. Use a text editor like vi or nano to create the text file called for-2.bash (eg. vi for-2.bash)

    If you are using the nano text editor, refer to notes on text editing in a previous week in the course schedule.

  33. Enter the following lines in your shell script:
    #!/bin/bash
    echo
    for x
    do
       echo $x
    done
    echo "blast-off!"
    echo


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

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

  36. Run your shell script by issuing: ./for-2.bash 10 9 8 7 6 5 4 3 2 1

    How does this differ from the previous shell script?

    You will learn in a couple of weeks more examples of using loop statements.

    Let's run a checking-script to confirm that both your for-1.bash and for-2.bash
    Bash shell scripts exist, have execute permissions, and when run, produce
    the same OUTPUT as required in this tutorial's instructions.

  37. Issue the following Linux command to run a checking script:
    bash /home/murray.saul/scripts/week10-check-3 | more

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

    Let's create a Bash shell script that contain user-created variables.

  39. After you complete the Review Questions sections to get additional practice, then work on your online assignment 3,
    sections 2 and 3 labelled Interactive Shell Environment and Introduction To Scripting (phone).

LINUX PRACTICE QUESTIONS

The purpose of this section is to obtain extra practice to help with quizzes, your midterm, and your final exam.

Here is a link to the MS Word Document of ALL of the questions displayed below but with extra room to answer on the document to simulate a quiz:

https://ict.senecacollege.ca/~murray.saul/uli101/uli101_week10_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:


PART A: WRITE BASH SHELL SCRIPT CODE

Write the answer to each question below the question in the space provided.


  1. Write a Bash shell script that clears the screen and displays the text Hello World on the screen.

    What permissions are required to run this Bash shell script?

    What are the different ways that you can run this Bash shell script from the command line?

  2. Write a Bash shell script that clears the screen, prompts the user for their full name and then prompts the user for their age,
    then clears the screen again and welcomes the user by their name and tells them their age.

    What comments would you add to the above script’s contents to properly document this Bash shell script to be understood
    for those users that would read / edit this Bash shell script’s contents?

  3. Write a Bash shell script that will first set the value of a variable called number to 23 and make this variable read-only.
    Then the script will clear the screen and prompt the user to enter a value for that variable called number to another value.
    Have the script display the value of the variable called number to prove that it is a read-only variable.

    When you ran this Bash shell script, did you encounter an error message?
    How would you run this Bash shell script, so the error message was NOT displayed?

  4. Write a Bash shell script that will clear the screen and then display all arguments that were entered after your Bash shell script when it was run. Also have the Bash shell script display the number of arguments that were entered after your Bash shell script.


PART B: WALK-THRUS

Write the expected output from running each of the following Bash shell scripts You can assume that these Bash shell script files have execute permissions. Show your work.

Walkthru #1:
cat walkthru1.bash
#!/usr/bin/bash
word1=”counter”
word2=”clockwise”
echo “The combined word is: $word2$word1”
WRITE OUTPUT FROM ISSUING:
./walkthru1.bash


Walkthru #2:
cat walkthru2.bash
#!/usr/bin/bash
echo “result1: $1”
echo “result2: $2”
echo “result3: $3”
echo “result 4:”
echo “$*”
WRITE OUTPUT FROM ISSUING:
./walkthru2.bash apple orange banana