Unit 3 : Shell Scripting in Linux

Unit 3 : Shell Scripting in Linux
- 3.1 Creating and Executing Shell Scripts (nano, vi, ./script.sh)
- 3.2 Shell Metacharacters and Operators
- 3.2.1 Filename Expansion (wildcards: *, ?, [])
- 3.2.2 Input/Output Redirection (>, >>, <)
- 3.2.3 Pipes (|)
- 3.2.4 Command Substitution ($(…), …)
- 3.3 Control Flow Structures (if-else, case, for, while, until)
- 3.4 Logical Operators (&&, ||, !)
- 3.5 test and [ ] command for Condition Testing (file, numeric, string)
- 3.6 Arithmetic Operations (expr, $(( )))
NOTES
1. Introduction to Shell Scripts
A shell script is a file containing a sequence of commands that are executed by the shell in Unix/Linux. Instead of typing commands one by one, you can store them in a .sh
file and run them as a program.
Why Use Shell Scripts?
Automation: Repeated tasks (backups, monitoring, system updates) can be automated.
Convenience: Run multiple commands with one file.
Custom Tools: Create your own command-line programs.
File Extension: Usually .sh
(example: myscript.sh
).
Interpreter: The Bash shell (#!/bin/bash
) is most common.
2. Steps to Create and Execute Shell Scripts
Step 1: Open a Text Editor
We can use nano (simple) or vi (powerful) to write scripts.
2.1 Using nano
Editor (Beginner-friendly)
Theory:nano
is a terminal-based text editor that allows simple creation and editing of files.
Practical Example:
Save & Exit:
Press CTRL + O → Press Enter to save.
Press CTRL + X to exit.
2.2 Using vi
Editor (Advanced)
Theory:vi
is a modal editor — it has command mode and insert mode. You need to switch between modes to edit or save.
Practical Example:
Press
i
→ Enter Insert Mode.Type:
4. How ./script.sh
Works
./
means current directory.script.sh
is the file name.The system uses the shebang line (
#!/bin/bash
) to determine which interpreter runs the file.
5. Tips for Writing Shell Scripts
Always start with
#!/bin/bash
.Use comments (
# This is a comment
) for clarity.Test commands one by one before putting them in the script.
Keep scripts readable with indentation and spacing.
1. Introduction to Shell Metacharacters & Operators
In a Unix/Linux shell, metacharacters are special characters that have a specific meaning to the shell. They are not treated as ordinary text but as instructions to control how commands are interpreted or executed.
Operators, on the other hand, are special symbols used for performing operations like redirection, piping, conditional execution, etc.
Without them, the shell would only execute commands literally — metacharacters give the shell its power and flexibility.
2. Shell Metacharacters
Here are the most commonly used shell metacharacters:
Metacharacter | Meaning | Example |
---|---|---|
* | Wildcard – matches zero or more characters | ls *.txt (lists all .txt files) |
? | Matches exactly one character | ls file?.txt (matches file1.txt, file2.txt) |
[] | Matches a range or set of characters | ls file[1-3].txt |
{} | Brace expansion – generates multiple patterns | echo file{1,2,3}.txt |
; | Command separator – run multiple commands sequentially | date ; who |
& | Run a process in the background | sleep 10 & |
&& | Run the second command only if the first succeeds | mkdir test && cd test |
| | Pipe – send output of one command to another | ls | grep file |
> | Redirect output to a file (overwrite) | echo "Hello" > file.txt |
>> | Append output to a file | echo "World" >> file.txt |
< | Take input from a file | wc -l < file.txt |
# | Comment – ignored by shell | # This is a comment |
\ | Escape special meaning of a character | echo \* (prints *) |
" | Preserve spaces but allow variable expansion | echo "My name is $USER" |
' | Preserve literal value of everything inside | echo 'My name is $USER' |
`command` |
Command substitution (older method) | echo `date` |
$(command) |
Command substitution (modern method) | echo $(date) |
~ | Home directory shortcut | cd ~ |
3. Shell Operators
Operators can be grouped into logical, arithmetic, and redirection types.
Logical Operators in Linux
Logical operators in Linux are used mainly in conditional expressions inside shell scripts or command-line statements to make decisions based on true/false conditions.
They are often used with test commands ([ ]
, [[ ]]
), loops, and if
statements.
Linux supports these main logical operators:
1. AND Operator (&&
)
Purpose: Runs the second command only if the first command is successful (exit status 0).
Exit Status Rule:
If the first command fails (non-zero exit status), the second command will not execute.
Usage in Scripts: Often used to ensure the second operation happens only if the first was successful.
Syntax:
2. OR Operator (||
)
Purpose: Runs the second command only if the first command fails.
Exit Status Rule:
If the first command succeeds, the second is skipped.
Useful for error handling.
Syntax:
3. NOT Operator (!
)
Purpose: Reverses the result of a condition.
Exit Status Rule:
If a condition is true,
!
makes it false.If a condition is false,
!
makes it true.
Syntax:
4. Logical AND (-a
) in Test Conditions
Works inside
[ ]
or[[ ]]
for multiple conditions.Syntax:
5. Logical OR (-o
) in Test Conditions
Works inside
[ ]
or[[ ]]
for checking if either condition is true.Syntax:
Practical Demonstration
Create a script to check multiple conditions:
3.2 Arithmetic Operators in Linux
Arithmetic operators in Linux are used to perform mathematical operations like addition, subtraction, multiplication, division, and modulus.
Since the Linux shell is primarily designed for command execution (not for complex math), we use specific utilities and syntax to perform calculations.
The two most common methods are:
Using
expr
(External command)Using
(( ))
(Bash built-in arithmetic expansion)
1. Arithmetic Operators in Linux
Operator | Description | Example (a=5, b=3) |
---|---|---|
+ | Addition | a + b = 8 |
- | Subtraction | a - b = 2 |
* | Multiplication | a * b = 15 |
/ | Division (integer result in shell) | a / b = 1 |
% | Modulus (remainder) | a % b = 2 |
** | Exponentiation (only in (( ))) | a ** b = 125 |
2. Using expr
Command
expr
is an external program that evaluates expressions.
Syntax:
Example:
3. Using (( ))
in Bash
(( ))
is an arithmetic evaluation syntax built into the shell.
It supports integer math and allows direct use of variables without $
.
Syntax:
Example:
4. Practical Script Example
Key Differences Between expr
and (( ))
Feature | expr | (( )) |
---|---|---|
Type | External command | Bash built-in |
Speed | Slower (runs separate process) | Faster (built into shell) |
Syntax | Requires $ and escaping * | No $ required for vars |
Data Type | Works with integers only | Works with integers only |
Exponentiation | Not supported | Supported (**) |
3.3 Redirection Operators in Linux
Introduction
In Linux, redirection is a feature that changes the standard input/output of commands.
By default:
Standard Input (stdin) → comes from the keyboard (file descriptor 0)
Standard Output (stdout) → goes to the terminal screen (file descriptor 1)
Standard Error (stderr) → also goes to the terminal (file descriptor 2)
Redirection operators allow you to send output to files instead of the screen, take input from files instead of the keyboard, or redirect errors to specific locations.
Types of Redirection Operators
1. Output Redirection (>
and >>
)
>
→ Redirects output to a file (overwrites if file exists)>>
→ Redirects output to a file (appends if file exists)
Example:
2. Input Redirection (<
)
Redirects the input of a command from a file instead of the keyboard.
Example:
3. Redirecting Standard Error (2>
, 2>>
)
2>
→ Redirects error messages to a file (overwrites)2>>
→ Redirects error messages to a file (appends)
Example:
4. Redirecting Both stdout and stderr
&>
→ Redirects both standard output and error to a file (overwrite)&>>
→ Redirects both standard output and error to a file (append)
Example: