Untitled
DevOps Lecture Notes: Scripting and Cron Jobs
Instructor and University Information
- Instructor: Muhammad Maaz Sheikh
- University: DHA Suffa - Computer Science Department
- Date: 14 April 2026
- Lecture Number: 06
Lecture Agenda
- Recap of Lecture 5
- Functions
- Concept of functions
- Writing functions
- Calling functions
- Passing arguments to functions - Arguments and Exit Codes
- Examples of using$1,$2, and$? - Cron Jobs
- Scheduling scripts automatically
- Common symbols used in Cron Jobs
- Detailed examples of Cron Jobs
- Steps to add and manage Cron Jobs
Recap of Lecture 5
- File Permissions
- Command:ls -lashows permissions:rwxfor Owner, Group, and Others.
- Command:chmod +xmakes a file executable.
- Command:chmod 755provides full control.
- Command:chmod 600restricts access to owner only for sensitive files. - Shell Script Basics
- Start scripts with:#!/bin/bash
- Create scripts using an editor likenano.
- Make scripts executable with:chmod +x
- Execute scripts with:./script.sh - Variables
- Example:NAME="Ali"— no spaces allowed in variable assignment.
- Use variable values with$NAME.
- Capture command output using$(...).
- Prompt users for input with:read -p. - Conditions
- Structure:if [ condition ]; then ... elif ... else ... fi
- Common operators:-eq,-gt,-lt,-f,-d,-z - Loops
- For loop:for X in list; do ... done
- While loop:while [ condition ]; do ... done
Understanding Functions
- Definition of a Function: A function is a named block of code that is repeatedly called, allowing for code reuse without redundancy.
- Benefits of Using Functions: Instead of rewriting the same lines of code, encapsulate them in a function and call it multiple times.
- Without Function Example:bash # Check git echo "[12:00] Checking git" command -v git ... # Check curl echo "[12:00] Checking curl" command -v curl ...
- With Function Example:bash check_tool() { echo "Checking $1" command -v $1 ... } # Call it many times: check_tool git check_tool curl check_tool node - Function Structure:
function_name() {
code here
}
```
- Call function by its name: `function_name`
- Arguments passed to a function can be referred to as `$1`, which is the first argument.
## Example Shell Script for Functions Implementation
- **Step 1:** Create script file.
- **Step 2:** Open the newly created file.
- **Step 3:** Write script with functions:
bash
#!/bin/bash
greet_user() {
echo "Welcome to Shell Scripting Functions Demo"
}
show_directory() {
echo "Current Directory:"
pwd
}
create_project() {
echo "Creating project folder…"
mkdir devops_project
echo "Folder created successfully!"
}
echo "Running Script…"
greet_user
show_directory
create_project
echo "Script Execution Completed"
```
- Expected Output after Execution:
Running Script...
Welcome to Shell Scripting Functions Demo
Current Directory: /home/student
Creating project folder...
Folder created successfully!
Script Execution Completed
```
## Passing Values When Running a Script
- Arguments passed to scripts are represented as:
- `$1`: First argument
- `$2`: Second argument
- `$#`: Total number of arguments
- `$@`: List of all arguments
- `$?`: Exit code of the last command executed (0 for success, non-zero for error)
- **Example Script Call**:
bash
./deploy.sh production v2.0``
- Breakdown:
-$0:./deploy.sh
-$1:production
-$2:v2.0
-$#:2`
- Inside the script:
ENV=$1
VERSION=$2
echo "Deploying $VERSION to $ENV"
if [ -z "$1" ]; then
echo "Usage: ./deploy.sh <env>"
exit 1
fi
```
## Writing the Script Line by Line
- Create file `args.sh`:
bash
#!/bin/bash
if [ -z "$1" ]; then
echo "Usage: ./args.sh
exit 1
fi
NAME=$1
CITY=${2:-"Unknown"}
echo "Hello $NAME!"
echo "You are from $CITY"
```
- Test Cases:
-./args.sh Ali(only one argument: check CITY)
-./args.sh(no argument: verify error message)
Communicating Success or Failure in Scripts
- Every command in Linux returns an exit code:
- 0 means SUCCESS
- Non-zero values (e.g., 1, 2, 127…) indicate ERROR - Checking Exit Code: The
$?variable contains the exit code of the last executed command.
- Example:bash ls /tmp echo $? # prints: 0 ls /fakefolder echo $? # prints: 2 - Using Exit Codes in scripts to manage flow:
git pull origin main
if [ $? -eq 0 ]; then
echo "Pull successful!"
npm install
else
echo "Pull failed! Stopping."
fi
```
## Cron Jobs: Automating Script Execution
- **Definition**: Cron is a built-in time-based job scheduler in Linux used for automating the execution of scripts at specified times.
- **Cron Syntax**: Uses a format of 5 fields followed by the command to run:
- Minute (0–59)
- Hour (0–23)
- Day of Month (1–31)
- Month (1–12)
- Day of Week (0–6)
- **Example:** `*/5 * * * * /path/to/script.sh`
## Common Cron Job Examples
- `* * * * *` = Every single minute
- `0 * * * *` = Every hour at :00
- `0 2 * * *` = Every day at 2:00 AM
- `*/5 * * * *` = Every 5 minutes
- `0 0 * * 0` = Every Sunday at midnight
- `0 9 * * 1-5` = Monday through Friday at 9:00 AM
## Common Symbols Used in Cron
- **Symbols**:
- `*`: Matches every value (e.g., every minute)
- `,`: Matches multiple values (e.g., at 9 AM and 5 PM)
- `-`: Specifies a range (e.g., every hour between 9 AM and 5 PM)
- `/`: Defines a step value or interval (e.g., every 15 minutes)
## Real Example of a Cron Job
- **Example Cron Job**: A script named `check_server.sh` runs every 5 minutes to monitor server health.
## Adding and Managing Cron Jobs Step by Step
1. **Create the script**:
bash
#!/bin/bash
echo "CPU: $(uptime)" >> /tmp/health.log``
- Create file:nano health.sh`
- Make the script executable:
chmod +x health.sh
```
3. **Organize scripts**:
- Move script to dedicated directory:
```bash
mv health.sh ~/scripts/health.sh
```
4. **Edit the crontab**:
- Open crontab:
```bash
crontab -e
```
5. **Add the cron job**:
bash
*/5 * * * * /home/user/scripts/health.sh
```
- Save and exit:
- Save changes using:Ctrl+X, pressY, thenEnter. - Verify the cron job was saved:
bash crontab -l - Check execution:
- Wait for 5 minutes and review log contents:bash cat /tmp/health.log
Key Takeaways from Lecture 6
- Functions: Defined with
func() { }, called by name, and help avoid repetitive code. - Arguments: Passed as
$1,$2, counting with$#, and accessible as$@. - Exit Codes:
$?indicates success (0) or error (non-zero). Useexit 0for success andexit 1for errors in scripts. - Cron Jobs: Schedule scripts using
*/5 * * * *for every 5 minutes. Usecrontab -eto edit andcrontab -lto list existing cron jobs. Always use the full path for scripts.