Module 21: Linux and Scripting

CompTIA A+ Core 2 (220-1102)

1. Linux Basics

  • Linux is an open-source, Unix-like OS; the kernel plus tools form a distribution (distro) such as Ubuntu, Debian, Fedora, Red Hat/CentOS, Mint, Arch

  • Used heavily on servers, embedded devices, Android (Linux kernel), and desktops

  • Desktop environments: GNOME, KDE, Xfce; the shell (usually bash) is the command interpreter

  • File systems: ext4 (most common), XFS, Btrfs; can read NTFS/FAT with drivers

  • Package managers install software:

Family

Tool

Package type

Debian/Ubuntu

apt / dpkg

.deb

Red Hat/Fedora

dnf / yum / rpm

.rpm

Arch

pacman


Universal

Snap, Flatpak


2. Directory Structure (Filesystem Hierarchy)

Path

Contents

/

Root of the whole file system

/home

User home directories

/root

The root user's home

/bin, /sbin

Essential commands, system admin commands

/etc

Configuration files

/var

Variable data: logs (/var/log), spool

/tmp

Temporary files

/usr

User programs and libraries

/dev

Device files

/proc

Virtual process and kernel info

/mnt, /media

Mount points for drives

/boot

Kernel and boot loader files

/opt

Optional software

  • Everything is a file; paths use / and are case-sensitive

  • ~ = home directory, . = current directory, .. = parent directory

3. Essential Commands

Navigation and Files

Command

Purpose

pwd

Print working directory

ls, ls -l, ls -a, ls -la

List files (long, hidden, both)

cd, cd .., cd ~

Change directory

mkdir, rmdir

Create / remove directory

touch

Create empty file or update timestamp

cp, cp -r

Copy (recursive for folders)

mv

Move or rename

rm, rm -r, rm -rf

Delete (-r recursive, -f force; dangerous)

cat, less, more, head, tail, tail -f

View files; -f follows logs

nano, vi/vim

Text editors

find

Search by name/attributes

grep

Search text patterns; grep -i, -r

man command

Manual page; --help shows quick help

ln -s

Symbolic link

tar, gzip, zip

Archive/compress

wc, sort, uniq, cut

Text processing

history, clear, echo

Shell utilities

Pipes and Redirection

  • | sends output of one command to another: ls | grep txt

  • > writes output to a file (overwrites); >> appends; < reads input; 2> redirects errors

Users, Permissions, and Admin

Command

Purpose

sudo

Run a command with superuser rights

su

Switch user

whoami, id

Show current user

passwd

Change a password

useradd, usermod, userdel, groupadd

Manage accounts and groups

chmod

Change permissions

chown / chgrp

Change owner / group

shutdown, reboot

Power control

System and Process Management

Command

Purpose

ps, ps aux, top, htop

View processes

kill PID, kill -9 PID, killall

Stop processes

df -h

Disk space on file systems

du -sh

Folder size

free -h

Memory usage

uname -a

System info

uptime

Load and run time

lsblk, fdisk -l, mount, umount

Disks and mounts

systemctl status/start/stop/enable

Manage services (systemd)

journalctl

View system logs

dmesg

Kernel/hardware messages

crontab -e

Schedule recurring jobs

Networking

ip addr (or ifconfig), ping, traceroute, netstat / ss, nslookup / dig, curl, wget, ssh user@host, scp, iwconfig

4. Permissions

ls -l output: -rwxr-xr-- 1 user group 4096 date file

  • First character: - file, d directory, l link

  • Then three triplets: owner / group / others, each r (read) w (write) x (execute)

Permission

Number

read

4

write

2

execute

1

  • chmod 755 file → owner rwx, group r-x, others r-x

  • chmod 644 file → owner rw-, group r--, others r--

  • chmod 600 → owner only; chmod 777 → everyone full (avoid)

  • Symbolic: chmod u+x file, chmod go-w file

  • Directories need x to be entered

  • Root (UID 0) is the superuser; use sudo rather than logging in as root

5. Backup, Updates, and Software

  • Back up with rsync, tar, cp -a, Timeshift (snapshots), or cloud tools; schedule with cron

  • Updates: sudo apt update && sudo apt upgrade (Debian/Ubuntu); sudo dnf upgrade (Fedora/RHEL)

  • Update vs. upgrade (apt): update refreshes the package list; upgrade installs newer versions

  • Install: sudo apt install package; remove: sudo apt remove package

  • Verify downloads with checksums and install from trusted repositories

6. Linux Security

  • Use strong passwords, limit sudo, keep systems patched

  • Firewalls: iptables, ufw (Ubuntu), firewalld

  • SSH with keys (ssh-keygen), disable root login

  • SELinux / AppArmor enforce access policy

  • Encryption: LUKS for disks

  • Check logs in /var/log (auth.log, syslog)

  • Run services with least privilege

7. Troubleshooting Linux

Problem

Approach

Won't boot

Check GRUB boot loader, use recovery mode / live USB, fsck for file-system errors

Disk full

df -h, du -sh *, clear logs/caches

Service down

systemctl status, journalctl -u service

No network

ip addr, ping, systemctl restart NetworkManager

Permission denied

ls -l, chmod/chown, use sudo

High CPU/memory

top/htop, kill the process

Package errors

Update lists, fix broken packages, check repos

Kernel panic

Boot an older kernel from GRUB

Forgotten password

Recovery mode or live media

  • GRUB is the common boot loader; fsck repairs file systems (run on unmounted volumes)

8. Scripting Basics

What Scripting Is For

Automates repeated tasks (backups, user creation, log checks, updates, cleanups, inventory) and reduces human error.

Common Script Types and Extensions

Language

Extension

Platform

Notes

Batch

.bat

Windows

Runs in CMD; simple automation

PowerShell

.ps1

Windows (and cross-platform)

Object-based, cmdlets (Get-Process)

Shell (Bash)

.sh

Linux/macOS

Starts with a shebang #!/bin/bash

Python

.py

Cross-platform

Readable, popular for automation

JavaScript

.js

Web/Node

Browser and server scripts

VBScript

.vbs

Windows

Legacy

Bash Script Essentials

#!/bin/bash
# This is a comment
name="Student"          # variable (no spaces around =)
echo "Hello, $name"      # output; $ reads a variable

if [ -f /etc/hosts ]; then
  echo "File exists"
else
  echo "Missing"
fi

for i in 1 2 3; do
  echo "Number $i"
done
  • Make executable: chmod +x script.sh, run with ./script.sh

  • Comments start with # (Bash/Python), REM or :: (Batch), # (PowerShell)

  • Exit codes: 0 = success; non-zero = error ($? holds the last code)

Core Programming Concepts (exam level)

Concept

Meaning

Variable

Named storage for a value

Constant

A value that doesn't change

Data types

String, integer, float, Boolean, array/list

Operators

Math (+ - * /), comparison (== != < >), logical (AND, OR, NOT)

Conditionals

if / else / elif

Loops

for, while, until — repeat actions

Functions

Reusable named blocks

Comments

Notes ignored by the interpreter

Arguments / parameters

Inputs to a script

Environment variables

System-wide values (e.g., PATH)

Error handling

Check exit codes, use try/catch (Python/PowerShell)

Batch and PowerShell Snippets

@echo off
echo Hello
pause
Get-Process | Where-Object { $_.CPU -gt 100 }
Get-Service | Sort-Object Status
  • PowerShell execution policy controls whether scripts may run (Set-ExecutionPolicy)

  • Windows tools to schedule scripts: Task Scheduler; Linux: cron

Script Safety Considerations

  • Test in a safe environment first

  • Beware of unintentional infinite loops, wrong paths, destructive commands (rm -rf, del /s)

  • Don't hard-code passwords; protect credentials

  • Run least privilege; review scripts from unknown sources (malware often arrives as scripts)

  • Document scripts and keep them in version control

9. Linux Cheat Sheet by Task

I want to…

Command

See where I am

pwd

List hidden files

ls -a

Make a folder

mkdir name

Copy a folder

cp -r src dest

Rename a file

mv old new

Read a log live

tail -f /var/log/syslog

Find text in files

grep -r "text" .

Check free disk

df -h

Check memory

free -h

Find the IP address

ip addr

Kill a stuck process

kill -9 PID

Install software

sudo apt install pkg

Make a file executable

chmod +x file

Run as admin

sudo command

Additional Textbook Topics: Uses for Scripting

  • Automate repetitive tasks: backups, user creation, cleanup, installs

  • Configuration and deployment: set up many machines the same way

  • Monitoring and reports: check disk space, services, and logs

  • Restart services, rename or move files in bulk, map drives at logon (login scripts)

  • Scheduled jobs: Task Scheduler (Windows), cron (Linux/macOS)

  • Reduce errors and save time, but test first and avoid hard-coded passwords

Quick-Reference Exam Points

  • Linux is case-sensitive; / is root; ~ is home

  • chmod: r=4, w=2, x=1; 755 and 644 are classics; chown changes owner

  • > overwrites, >> appends, | pipes

  • apt update refreshes lists; apt upgrade installs; sudo = temporary admin

  • ps/top view processes, kill ends them, df = disk space, grep = search text

  • Shebang #!/bin/bash starts a shell script; extensions: .bat, .ps1, .sh, .py, .js, .vbs

  • Shell scripts: variables, if, loops (for/while), functions, comments

  • fsck repairs file systems; GRUB is the boot loader

  • Don't hard-code credentials in scripts; test before running on production