System Scripting Lab 2

Exercise 1: Environment Variables Script

#!/bin/bash

# Print all environment variables to terminal
echo "Printing environment variables:"
printenv

# Save environment variables to a file
printenv > env_variables.txt

# Count number of lines (entries) in file
count=$(wc -l < env_variables.txt)

# Print result
echo "Number of environment variables: $count"

Explanation:

Exercise 2: Script Arguments

#!/bin/bash

# Print script name
echo "Script name: $0"

# Print number of arguments
echo "Number of arguments: $#"

# Print all arguments
echo "Arguments passed: $@"

Explanation:

Example Run:

./script.sh one two three

Exercise 3: Script with Input Arguments

#!/bin/bash

# Assign input arguments
folderName=$1
fileName=$2
content=$3

# Create folder
mkdir "$folderName"

# Create file inside folder
touch "$folderName/$fileName"

# Write content into file
echo "$content" > "$folderName/$fileName"

# Display file content
cat "$folderName/$fileName"

Explanation:

Scheduling with at

Check service

service atd status

Install if needed

sudo apt-get install at

Start/Stop service

service atd start
service atd stop

Schedule a job

at 16:15
cp -r $HOME/Documents $HOME/Main
CTRL + D

List jobs

atq

Remove job

atrm JOB_NUMBER

Exercise 4: Schedule Jobs with at

Job 1: Create folder

at 16:10
mkdir testFolder
CTRL + D

Job 2: Create file

at 16:12
touch testFolder/file.txt
CTRL + D

Job 3: Rename folder

at 16:14
mv testFolder renamedFolder
CTRL + D

Verify using:

atq
ls

Exercise 5: Schedule Script with at

at 16:20
./welcome.sh
CTRL + D

Scheduling with cron

Check cron service

service cron status

Edit cron jobs

crontab -e

Format

* * * * * command
| | | | |
| | | | ---- Day of week (0-6)
| | | ------ Month (1-12)
| | -------- Day of month (1-31)
| ---------- Hour (0-23)
------------ Minute (0-59)

Example

*/2 * * * * cp -r $HOME/Documents $HOME/croMain

List cron jobs

crontab -l

Exercise 6: Daily Script with cron

crontab -e
*/2 * * * 2 ./script.sh

Explanation:

Exercise 7: Logging Script

Script: log_script.sh

#!/bin/bash

# Append message with timestamp to log file
echo "Log entry at $(date)" >> log.txt

Schedule with cron

crontab -e
*/2 * * * * ./log_script.sh

Verify:

cat log.txt

Explanation:

Key Exam Tips