System Scripting Lab 05

User Accounts, AWK, SED

Setup

mkdir lab05
cd lab05

Exercise 1: User Account Script

#!/bin/bash

# Check if script is run as root
if [ "$EUID" -ne 0 ]; then
    echo "Run as root (use sudo)"
    exit 1
fi

# Check if username provided
if [ $# -ne 1 ]; then
    echo "Usage: $0 username"
    exit 1
fi

username=$1

# Create user
echo "Creating user: $username"
useradd "$username"

# Show users
echo "User list after creation:"
cut -d: -f1 /etc/passwd

# Wait 10 seconds
sleep 10

# Delete user
echo "Deleting user: $username"
userdel "$username"

# Show users again
echo "User list after deletion:"
cut -d: -f1 /etc/passwd

Explanation:

AWK Basics

ls -l | awk '{print $3 $5 $9}'
ls -l | awk '{print $1 " " $5 " " $3}'

Difference:

Exercise 2: Username & UID with AWK

#!/bin/bash

# Extract username and UID
awk -F: '{print $1 " " $3}' /etc/passwd > users.txt

# Display file
cat users.txt

# Exclude system users (UID < 1000 typically)
awk -F: '$3 >= 1000 {print $1 " " $3}' /etc/passwd

Explanation:

Exercise 3: File Size Calculation (AWK)

#!/bin/bash

# Initialize totals
awk '
BEGIN {
    totalBytes=0;
    totalBlocks=0;
    print "File Name: Byte size Block size"
}
{
    if ($1 == "total") next;

    bytes=$5;
    blocks=int(($5+4095)/4096); # approximate block size

    totalBytes += bytes;
    totalBlocks += blocks;

    print $9 " " bytes " bytes " blocks " blocks";
}
END {
    print "Total bytes " totalBytes " bytes";
    print "Total blocks " totalBlocks " blocks";
}' <(ls -l)

Explanation:

SED Basics

sed -e 's/coat/bag/g' fileCon.txt

Explanation:

Exercise 4: Change Default Shell

#!/bin/bash

# Replace /bin/bash with /bin/sh
sed 's#/bin/bash#/bin/sh#g' passwd_copy.txt > updated_passwd.txt

Explanation:

Exercise 5: SED Text Processing

content.txt

Hello Jerry how are you? Jerry, I heard you like scripting.
Jane will be around tomorrow to look after you.
I hope you Jerry will keep off scripting and be nice to her.
What about Kate? Tell me the story.
I would be delighted to see you progress.

Script

#!/bin/bash

# Replace second occurrence of Jerry with Jones
sed '0,/Jerry/s//Jones/2' content.txt > temp.txt

# Delete last two lines
sed '$d' temp.txt | sed '$d' > final.txt

# Display result
cat final.txt

Explanation:

Key Exam Tips