Topic 7 Linux Unit 3
Topic 7 Linux Unit 3
touch script.sh
o Explanation: touch script.sh creates an empty file named script.sh. This file will
contain our shell script commands.
2. Give executable permission to the shell script file:
chmod +x script.sh
nano script.sh
oExplanation: nano script.sh opens the script.sh file in the nano text editor,
allowing you to write or edit the script’s content.
4. Add content to the script: Inside the editor, add the following line:
#!/bin/bash
read num1
sum=$((num1 + num2))
#!/bin/bash: This tells the system to use the bash shell to execute the script.
echo: Prints messages to the terminal.
read: Reads user input and stores it in variables (num1 and num2).
$((...)): Performs arithmetic operations; in this case, it adds num1 and num2.
echo: Prints the result of the addition.
./script.sh
o Explanation: ./script.sh executes the script. The ./ before the filename tells the
shell to look for the file in the current directory and execute it.
Shell variables
In shell scripting, variables are used to store data values which can be accessed and modified
throughout the script.
1. Defining Variables
A variable is created simply by assigning a value to a name, with no spaces around the =
sign.
Example:
name="Alice"
age=25
Use the $ symbol followed by the variable name to retrieve its value.
Example:
Local Variables: These are defined within a script or function and are accessible only
within that scope.
Environment Variables: These are available to any child processes created by the shell.
They are typically uppercase by convention (e.g., PATH, HOME).
Positional Parameters: Special variables for accessing command-line arguments passed
to the script (e.g., $1, $2, etc.).
Special Variables: Variables like $? (last command's exit status), $$ (current script's
process ID), $# (number of arguments passed), etc.
4. Positional Parameters
Example:
5. Assigning Values
Variables can be assigned directly, or their values can be derived from commands.
Example:
6. Add two variables directly using $(...) or by using external program expr
var1=10
var2=20
sum=$(($var1 + $var2))
echo $sum
Output:
30
var1=10
var2=20
echo $sum
Output:
30
Example:
echo "Exit status: $?"
Sleep and Wait
In shell scripting, the commands sleep and wait are used for controlling the timing and execution
flow of scripts.
1. sleep Command
The sleep command pauses the execution of the script for a specified number of
seconds.
It is often used to delay operations or give time for other processes to complete.
You can specify the time in seconds (e.g., sleep 5), or with a suffix for minutes (m),
hours (h), or days (d).
Example:
echo "Starting..."
2. wait Command
The wait command pauses the execution of the script until specified background
processes finish.
By default, wait will wait for all background jobs to complete if no job ID or PID is
provided.
It’s commonly used to synchronize processes within a script, ensuring certain processes
complete before moving on.
sleep 5 &
pid1=$!
sleep 10 &
pid2=$!
Script Termination
Termination with exit: The exit command terminates the script and optionally returns
a status code. This is often used to end the script if a critical error occurs or to indicate
successful completion.
Exit Codes: Exit codes help other scripts or commands understand whether a script
executed successfully (exit 0) or encountered an error (exit with a non-zero code).
if [ ! -f "/path/to/file" ]; then
fi
In shell scripting, taking decisions typically involves using conditional statements to perform
different actions based on specific conditions. The main structures for decision-making in shell
scripting are if, if-else, and case statements.
1. if Statement
The if statement allows you to execute a block of code only if a specified condition is true.
Syntax:
if [ condition ]; then
fi
Example:
number=5
fi
2. if-else Statement
The if-else statement is used when you want to perform one action if a condition is true and a
different action if it is false.
Syntax:
if [ condition ]; then
else
fi
Example:
number=-3
else
fi
3. if-elif-else Statement
The if-elif-else statement allows you to check multiple conditions in sequence, executing
different code blocks based on the first condition that evaluates to true.
Syntax:
if [ condition1 ]; then
else
fi
Example:
number=0
else
fi
4. case Statement
The case statement is useful for handling multiple possible values for a single variable. It's often
used as an alternative to if-elif-else when there are many conditions to check.
Note: In shell scripting, esac is the closing keyword for a case statement. It’s simply “case”
spelled backward, and it signifies the end of the case block.
Syntax:
case variable in
pattern1)
;;
pattern2)
;;
*)
;;
esac
Conditional Operators:
String Comparisons:
o =: Equal
o !=: Not equal
o -z: String is empty
o -n: String is not empty
Numeric Comparisons:
o -eq: Equal
o -ne: Not equal
o -lt: Less than
o -gt: Greater than
o -le: Less than or equal
o -ge: Greater than or equal
File Tests:
o -e file: File exists
o -d file: File is a directory
o -f file: File is a regular file
o -s file: File is not empty
c. Loop Control Structure
In shell scripting, loop control structures allow you to repeat a set of commands multiple times.
The most common loop structures in shell scripting are for, while, and until. Each has its own
use case, depending on the condition you want to check for repeated execution.
1. for Loop
The for loop is used to iterate over a list of items, executing a set of commands for each item.
Syntax:
do
done
Example:
do
done
2. while Loop
The while loop executes a block of commands as long as a specified condition is true.
Syntax:
while [ condition ]
do
# Commands to execute while condition is true
done
Example:
count=1
do
count=$((count + 1))
done
Repeating tasks while a condition holds true, like waiting for a process to complete
Counting or generating a sequence until a specific limit is reached
3. until Loop
The until loop is similar to the while loop but with an opposite condition; it runs until the
specified condition becomes true.
Syntax:
until [ condition ]
do
done
Example:
count=1
count=$((count + 1))
done
Performing tasks until a specific condition is met, like waiting for a service to start
Generally used when you want to run the loop as long as a condition is false
for i in 1 2 3 4 5
do
if [ $i -eq 3 ]; then
fi
if [ $i -eq 4 ]; then
fi
done
Output:
Number is: 1
Number is: 2
Skipping 3
Breaking at 4
5. Nested Loops
You can place one loop inside another, known as a nested loop. This is helpful for processing
multi-dimensional data, like tables or matrices.
Example:
for i in 1 2
do
for j in A B
do
done
done
Shell metacharacters are special characters in shell scripting that have a unique function, often
used to control input, output, and other aspects of how commands are executed. Here's a
breakdown of some commonly used shell metacharacters:
1. Wildcards
2. Redirection Operators
>>: Redirects standard output to a file, appending if the file already exists.
3. Pipes
&&: Executes the next command only if the previous command succeeds.
mkdir test && cd test # Creates and changes directory to "test" if mkdir succeeds
||: Executes the next command only if the previous command fails.
cd nonexistent || echo "Directory does not exist." # Prints message if directory change
fails
5. Command Substitution
6. Quoting
echo 'This $is a literal string' # Outputs: This $is a literal string
" " (Double Quotes): Preserves spaces and special characters but allows variable
expansion.
name="World"
echo "Hello $name" # Outputs: Hello World
7. Background Execution
sleep 10 & # Runs sleep in the background, allowing further commands to execute
immediately
8. Grouping Commands
(cd /tmp && ls) # Changes directory to /tmp and lists contents in a subshell
{ }: Groups commands in the current shell.
9. Conditional Expressions
Summary Table
Metacharacter Description
*, ?, [] Wildcards for matching filenames
>, >>, < Redirect output/input
` `
`command` or $(command) Command substitution
'' Single quotes, prevent variable expansion
"" Double quotes, allow variable expansion
\ Escape character
& Run command in background
( ), { } Group commands in subshell or current shell
[ ], [[ ]] Conditional expressions
<( ), >( ) Process substitution