Tutorial 10 - Shell Scripting - Part 1

From CDOT Wiki
Revision as of 13:36, 14 November 2021 by Jason Michael Carman (talk | contribs) (INVESTIGATION 1: CREATING A SHELL SCRIPT)
Jump to: navigation, search

Content under construction

INTRODUCTION TO SHELL SCRIPTING

Main Objectives of this Practice Tutorial

  • Plan and create a Shell Script
  • Explain the purpose of the she-bang line contained at the top of a shell script.
  • Set permissions and execute shell scripts.
  • Use environment and user-defined variables in shell scripts.
  • Use Command Substitution and Math Operations in shell scripts
  • Explain the purpose of the $? exit status and the test command.
  • Use if and if-else logic statements in shell scripts.
  • Use a for loop statement with a list in shell scripts.

Tutorial Reference Material

Course Notes
Linux Command/Shortcut Reference
Course Notes:


Shell Scripting

Variables

Commands / Techniques

Control Flow Statements

KEY CONCEPTS

A shell script is a file that contains Unix/Linux commands and reserved words to help automatic common tasks.

Creating & Executing Shell Scripts

It is recommended to plan out on a piece of paper the purpose of the shell script.
Once you have planned your shell script by listing the sequence of steps (commands),
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.
It is recommended to include a file extension that describes the type of shell for the shell script.

Using a Shebang Line

The shebang line must appear on the first line and at the beginning of the shell script.
Since Linux shells have evolved over a period of time, using a she-bang line forces the shell script
to run in a specific shell, which could prevent errors in case an older shell does not recognize
newer features from more recent shells.

The she-bang line is a special comment at top of your shell script to run your shell script
in a specific shell.

NOTE: 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 Shell Scripts

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

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


Variables / Parameters

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 that can be used in the shell script for customized purposes.

Data can be stored and removed within a variable using an equal sign (no spaces on either side of equal sign).

The read command can be used to prompt the user to enter data into a variable. The readonly command will prevent
the current value of the variable for the remainder of the execution of a shell script.

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 arguments contained in a shell script or using the set command.

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 filename 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:
$* , “$*” , "$@" , $# , $?

Command Substitution / Math Operations


Command Substitution:

Example of how a for loop with command substitution works.

Command substitution is a facility that allows a command
to be run and its output to be pasted back on the command line as arguments to another command.
Reference: https://en.wikipedia.org/wiki/Command_substitution

Usage:

command1 $(command2)
or
command1 `command2`


Examples:

file $(ls)
mail -s "message" $(cat email-list.txt) < message.txt
echo "The current directory is $(pwd)"
echo "The current hostname is $(hostname)"
echo "The date is: $(date +'%A %B %d, %Y')"


Math Operations:

Common Math Operator Symbols.

In order to make math operations work, we need to convert numbers
stored as text into binary numbers.

We can do this by using 2 pairs of round brackets (( )).

Examples:

num1=5;num2=10
echo “$(($num1 + $num2))”
15
echo “$((num1-num2))”
-5
((product=num1*num2))
echo “$product”
50


Control Flow Statements


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.

In order to use control flow statements, you need to test a condition to get
TRUE (zero value) or FALSE (non zero value). This can be done two ways:
  • Run a command to get the exit status ($?)
  • Use the test command

Refer to the diagrams on the right to see how to use the test command.

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 diagrams to the right test options and their purposes.

Logic Statements

A logic statement is used to determine which Linux commands
are executed basedon the result of a condition:
TRUE (zero value) or FALSE (non-zero value).

Example of using the if logic 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 to the right for using the if logic statement with the test command.






if-else statement:

Example of how an if-else control-flow statement.

Unlike using an if statement, an if-else statement take two different sets of actions
based on the results of the test condition.

Example:

if test condition
  then
     command(s)
  else
     command(s) 
fi


Loop Statements

Example of using the for looping control-flow statement.

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

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

In this investigation, you will learn how to create and run a 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 look at selecting an appropriate filename for your shell script.

  3. Issue the following linux command to check if the filename called hello
    already exists as a command:
    which hello

    The output from this command should indicate that the shell did NOT
    find any directories that contained this filename that could represent
    a command; therefore, this shell script name CAN be used.

    Using a text editor to add Linux commands in to the hello shell script.
  4. Use a text editor like vi or nano to create the text file called hello

  5. Enter the following two lines in your shell script:
    echo
    echo "Hello $USER"
    echo


    NOTE: The variable called USER is an environment variable that contains the current user's login name. If you wanted to share your shell script with other users, when they run the shell script, they will greeted by their username. Environment variables make your shell script adaptable by ALL users.

  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.

    An error message will appear when trying to run a shell script by name that does NOT have execute permissions.
    Output from running your hello shell script (YourUserID representing your username).
  7. Issue the following linux command to run your shell script in your current directory:
    ./hello

    You should notice an ERROR message indicating you don't have permissions to run the file. To fix this, you need to
    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. Issue the following to run your shell script:
    ./hello

    Did your shell script run?

    ATTENTION: Students might 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


  10. Issue the following Linux command to run a checking script:
    ~osl640/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.

Proceed to the next investigation.

INVESTIGATION 2: USING VARIABLES IN SHELL SCRIPTS

INVESTIGATION 3: COMMAND SUBSTITUTION / MATH OPERATIONS

INVESTIGATION 4: USING CONTROL FLOW STATEMENTS IN SHELL SCRIPTS

LINUX PRACTICE QUESTIONS