Tutorial 10 - Shell Scripting - Part 1
Content under construction
Contents
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
Since Linux shells have evolved over a period of time, using a she-bang line forces the shell scriptto 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
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
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:
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:
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
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).
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:
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
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.