mkdir lab05
cd lab05
#!/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:
$EUID → Checks root privileges/etc/passwd → Stores user infocut -d: -f1 → Extracts usernamesls -l | awk '{print $3 $5 $9}'
ls -l | awk '{print $1 " " $5 " " $3}'
Difference:
#!/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:
-F: → Sets field separator$1 → Username$3 → UID#!/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:
BEGIN → Runs before processingEND → Runs after processingint() → Integer conversionsed -e 's/coat/bag/g' fileCon.txt
Explanation:
s → Substituteg → Replace all occurrences#!/bin/bash
# Replace /bin/bash with /bin/sh
sed 's#/bin/bash#/bin/sh#g' passwd_copy.txt > updated_passwd.txt
Explanation:
# used instead of / to avoid conflictHello 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.
#!/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:
0,/pattern/ → Limits range$d → Deletes last line