Semester 7, 3 Credits
Staged review notice — read first
Status: supplementary. This guide is staged material provided for study and practice.
Source of course structure: The 2025 Tribhuvan University course structure lists BCA404-IV Linux, Semester 7, 3 credits. The official TU document confirms the course identity but has no detailed micro-syllabus or numbered unit outline. This guide is built from general Linux knowledge and pedagogical practice appropriate for a Bachelor of Computer Application semester-7 Linux course. It is not the official TU micro-syllabus.
Not official: This guide is not the official Tribhuvan University micro-syllabus. The official TU 2025 record publishes no numbered unit outline for this course. All topic titles, explanations, worked examples, labs, and review questions are original BCA Nepal study material created to ground the listed themes. Nothing here is copied from the TU source beyond the course code, semester, credit count, and subject name derived from the structure listing.
Teaching material: All explanations, labs, solved examples, diagrams, and practice exercises below are original BCA Nepal material designed for classroom and self-study use. They are intended to support learning the Linux topics appropriate for a semester-7 BCA course.
Safe practice: Use a virtual machine or personal test system for labs. Do not change settings on shared or production systems without authorization.
Course code: BCA404-IV
Semester: 7
Curriculum: 2025
Credits: 3
Subject: Linux
Outline status: Unverified — staged study guide, not the official TU micro-syllabus
Introduction
Linux is a Unix-like operating system kernel originally created by Linus Torvalds in 1991. It has become the foundation of most server infrastructure, embedded systems, and a growing desktop presence. For BCA students, Linux provides a practical environment for understanding operating-system concepts, developing server-side applications, and mastering the command-line tools that underpin modern software development and DevOps practices.
This guide covers the core topics typically expected in a semester-7 Linux course for the BCA program. Each section provides conceptual foundations, essential commands, and practical labs with solved examples and review answers. The material is organized thematically — not into numbered units — so you can study topics in the order that best suits your learning path.
Linux Architecture
The Linux operating system operates in two primary modes: user mode and kernel mode. The kernel is the core component that manages hardware access, memory, processes, and device communication. Surrounding the kernel are system libraries, shells, and utilities that provide the user interface and higher-level functions.
Key Concepts
- Kernel: The central core of Linux. It handles memory management, process scheduling, device drivers, and system calls. Kernels can be monolithic (most of the code in a single address space), microkernel (minimal kernel with services moved to user space), or modular (loadable kernel modules via
.kofiles). - System calls: The programmatic interface between a process and the kernel. Common system calls include
open(),read(),write(),exec(),fork(),exit(), andwait(). Every command you run in a shell ultimately triggers one or more system calls. - Shell: A user-level program that reads input from the keyboard or a script and executes commands via the system shell. Popular shells include
bash(Bourne Again SHell),zsh,fish, andsh. The shell interprets user commands and launches programs. - Filesystem hierarchy: Linux uses a hierarchical filesystem tree rooted at
/. Key directories include:/bin//sbin: Essential user-level binaries and system administration binaries./etc: Configuration files./home: User home directories./lib//lib64: Essential shared libraries needed to boot the system and run binaries in/binand/sbin./dev: Device files representing hardware devices./proc: Virtual filesystem providing process and kernel information./sys: Virtual filesystem exporting kernel device information./tmp: Temporary files, cleared on reboot./var: Variable data such as logs, mail queues, and printer buffers./usr: Secondary hierarchy for user commands and documentation./opt: Optional application software packages.
Lab: Exploring the Filesystem
# List the root directory and key subdirectories
$ ls /
$ ls /etc
$ ls /home
$ ls /var
# Display the current working directory and change directory
$ pwd
$ cd /tmp
$ cd /
Solved example: What does ls /home show on a typical BCA lab system? It lists the home directories of all user accounts, typically named after each student's username.
Review answers:
- Q: What is the top-level directory in the Linux filesystem hierarchy? A:
/(root). - Q: Which directory holds system configuration files? A:
/etc. - Q: What does the
/procfilesystem provide? A: Virtual filesystem exposing process and kernel information.
Commands and Files
Linux commands are executable files located primarily in /bin, /sbin, /usr/bin, and /usr/sbin. The man system provides online manual pages for most commands.
Command structure
Most Linux commands follow the pattern:
command [options] [arguments]
- command: The name of the executable.
- options: Flags that modify the command's behavior, typically starting with
-or--. - arguments: Paths, filenames, or other values the command operates on.
Common file-related commands
| Command | Description |
|---|---|
ls |
List directory contents. ls -l shows long format with permissions, owner, size, and modification time. ls -a shows hidden files (those starting with .). |
cd |
Change the current working directory. cd /path/to/directory changes to the specified directory; cd without arguments returns to the home directory; cd .. moves up one level. |
pwd |
Print the full path of the current working directory. |
mkdir |
Create a new directory. mkdir newdir creates newdir in the current location. mkdir -p /path/to/nested/dir creates nested directories, creating parent directories as needed. |
touch |
Create a new empty file or update the modification timestamp of an existing file. touch file.txt creates (or touches) file.txt. |
rm |
Remove (delete) files or directories. rm file.txt deletes the file. rm -r directory removes a directory and its contents recursively. rm -i prompts before every removal. rm -f forces removal without prompting. |
cp |
Copy files or directories. cp source destination copies a file. cp -r source_dir dest_dir copies a directory recursively. |
mv |
Move or rename files or directories. mv oldname newname renames a file or moves it to a new location. |
cat |
Concatenate and display file content. cat file.txt displays the file. cat file1 file2 > combined.txt concatenates multiple files into a new file. |
less |
View file content one page at a time. Press q to quit, arrow keys or Space to navigate. |
head |
Display the first 10 lines of a file. head -n file.txt displays the first n lines. |
tail |
Display the last 10 lines of a file. tail -n file.txt displays the last n lines. tail -f file.txt follows a file in real time, useful for watching logs. |
Pipes and redirection
|(pipe): Takes the output of the left command and feeds it as input to the right command. For example,ls -l | lesslists files one page at a time.>(output redirection): Redirects command output to a file, overwriting the file if it exists. For example,ls -l > filelist.txtwrites the long listing tofilelist.txt.>>(append redirection): Appends command output to an existing file without overwriting.<(input redirection): Provides a file as input to a command. For example,sort < unsorted.txtsorts the lines ofunsorted.txt.
Environment variables
$PATH: A colon-separated list of directories the shell searches when looking for executable commands.$HOME: The path to the current user's home directory.$?: The exit status of the last executed command.0typically means success; non-zero values indicate various error conditions.
Lab: Basic Command Practice
# Create a directory structure and practice commands
$ mkdir -p ~/lab/notes
$ cd ~/lab
$ touch myfirstfile.txt
$ ls -l
$ cp myfirstfile.txt mysecondfile.txt
$ ls -l
$ mv mysecondfile.txt renamed.txt
$ ls -l
$ rm renamed.txt
$ ls -l
$ pwd
Solved example: After running the lab sequence, ls -l after the rm command should show no files in the ~/lab directory (unless other files were created previously).
Review answers:
- Q: What does
ls -ashow thatlsdoes not? A: Hidden files (files whose names start with.). - Q: What is the difference between
rm fileandrm -r directory? A:rm filedeletes a single file;rm -r directoryremoves a directory and all its contents recursively. - Q: What does
head -5 file.txtdo? A: Displays the first 5 lines offile.txt.
Permissions
Every file and directory in Linux has three permission categories: owner, group, and others. Permissions control who can read, write, or execute a file.
Permission symbols
Permissions are represented as a three-digit octal number or a 10-character string.
Octal notation
Each permission group (owner, group, others) is assigned a sum of:
- 4 = read (r)
- 2 = write (w)
- 1 = execute (x)
The total for each group is the sum of its permissions. For example:
7= 4 + 2 + 1 = read + write + execute6= 4 + 2 = read + write5= 4 + 1 = read + execute4= read only2= write only1= execute only0= no permissions
Symbolic notation
The 10-character string format: permissions links owner group size month day time filename
The first character indicates the file type:
-= regular filed= directoryl= symbolic link
The next nine characters are grouped into three sets of three:
- First triplet (owner): rwx, rw-, r--, r-x, etc.
- Second triplet (group): rwx, rw-, r--, r-x, etc.
- Third triplet (others): rwx, rw-, r--, r-x, etc.
For example, -rwxr-xr-x means:
- Owner: read, write, execute (7)
- Group: read, execute (5)
- Others: read, execute (5)
Changing permissions with chmod
# Octal mode
$ chmod 755 script.sh # owner: rwx, group: r-x, others: r-x
$ chmod 644 document.txt # owner: rw-, group: r--, others: r--
# Symbolic mode
$ chmod u+x script.sh # add execute for owner
$ chmod g-rwx script.sh # remove all permissions for group
$ chmod o= script.sh # remove all permissions for others
$ chmod a+r file.txt # add read permission for all (owner, group, others)
Special permissions
- Setuid (s): When set on an executable, the program runs with the permissions of the file owner (usually root). Commonly used for commands that need temporary root access, such as
passwd(allows users to change their own password without full root access). - Setgid (s): When set on an executable, the program runs with the permissions of the file's group. When set on a directory, new files and subdirectories created within inherit the directory's group.
- Sticky bit (t): When set on a directory, only the file's owner, the directory's owner, or root can delete or rename files within that directory. Commonly used on
/tmpso users can create files but not delete each other's files.
Viewing and changing ownership with chown and chgrp
# Change file owner
$ chown newowner file.txt # change owner to newowner
$ chown newowner:newgroup file.txt # change owner and group
# Change group only
$ chgrp newgroup file.txt # change group to newgroup
# Recursive change
$ chown -R apache:apache /var/www # change owner and group recursively
Lab: Managing Permissions
# Create a script and set permissions
$ cd ~/lab
$ nano setup.sh # create a simple script (press Ctrl+X, Y, Enter to save)
$ chmod 755 setup.sh # make the script executable by everyone, readable/writable by owner
$ ./setup.sh # run the script
# Change permissions interactively
$ chmod u-x setup.sh # remove execute for owner
$ ls -l setup.sh # verify permissions changed
Solved example: After chmod 755 setup.sh, the script is executable by all users, and the owner can read and write it. Running ./setup.sh executes the script with the owner's permissions.
Review answers:
- Q: What does
chmod 644 fileset? A: Owner can read and write; group and others can read only. - Q: In the symbol string
-rwxr-xr-x, what does the firstrwxrepresent? A: Owner permissions (read, write, execute). - Q: What is the sticky bit used for on the
/tmpdirectory? A: Allows any user to create files in/tmp, but only the file's owner, the directory's owner, or root can delete or rename those files.
Processes
A process is a running instance of a program. Each process has a unique Process ID (PID), and the operating system manages processes through scheduling, signaling, and lifecycle control.
Process lifecycle
- Creation: A new process is created via the
fork()system call, which creates a child process that is a copy of the parent. The original process is the parent; the new process is the child. Afterfork(), both processes continue execution from the point of thefork()call, typically usingexec()in the child to replace its program image with a new program. - Execution: The scheduler decides which process runs on the CPU at any given time. Linux uses a Completely Fair Scheduler (CFS) that aims to give each process a fair share of CPU time.
- Termination: A process ends when it calls
exit()or when the kernel kills it (e.g., via a signal). The parent process can read the child's exit status usingwait()orwaitpid(). - Zombie: If a child process terminates but the parent has not yet read its exit status, the child becomes a "zombie" process. A zombie occupies a PID entry in the process table but consumes no system resources except the entry itself. The parent must call
wait()to reap the zombie.
Common process-related commands
| Command | Description |
|---|---|
ps |
Report a snapshot of current processes. ps aux shows all processes for all users with detailed information. ps -ef shows all processes in "full format." ps -u username shows processes for a specific user. |
top |
Display real-time system monitoring, including CPU and memory usage per process. Press q to quit. |
htop |
An interactive, colorized alternative to top with mouse support (may need installation). |
kill |
Send a signal to a process to terminate or modify its behavior. kill PID sends the default signal (TERM, termination request). kill -9 PID sends SIGKILL, which forcefully terminates the process immediately (cannot be caught or ignored). kill -l lists available signal names. |
pkill / killall |
Kill processes by name rather than PID. pkill firefox terminates all processes named firefox. killall httpd terminates all processes named httpd. |
nice |
Run a command with a modified scheduling priority. nice -n 10 command starts command with a nice value of 10 (lower priority, nicer to other processes). Nice values range from -20 (highest priority) to 19 (lowest priority). |
renice |
Change the nice value of a running process. renice -n 5 -p PID sets the priority of the process with the given PID to 5. |
jobs |
List active jobs in the current shell session, showing stopped and background jobs. |
fg |
Bring a background job to the foreground. fg %1 brings job number 1 to the foreground. |
bg |
Resume a stopped job in the background. bg %1 resumes job number 1 in the background. |
disown |
Remove a job from the shell's job table, so it is not killed when the shell exits. |
wait |
Pause the shell until a background job finishes. |
Process signals
Signals are software interrupts sent to a process to request action. Common signals include:
| Signal | Description |
|---|---|
| SIGTERM (15) | Termination request. The process can catch this signal and perform cleanup before exiting. This is the default signal sent by kill PID. |
| SIGKILL (9) | Immediate termination. The process cannot catch, catch, or ignore this signal. Use only when a process is unresponsive to SIGTERM. |
| SIGSTOP (19) | Immediate stop. The process cannot catch or ignore this signal. Used to pause a process. |
| SIGCONT (18) | Continue. Resumes a stopped process (one that was stopped via SIGSTOP or Ctrl+Z). |
| SIGINT (2) | Interrupt, usually triggered by Ctrl+C. The process can catch this signal to perform cleanup or ignore it. |
| SIGHUP (1) | Hangup. Originally sent when a terminal session disconnects. Many daemons re-read their configuration files when they receive SIGHUP. |
Listing and controlling processes
# View all processes
$ ps aux | head -20
# Find a specific process
$ ps -ef | grep apache
# Terminate a process by PID
$ kill 3947
# Forcefully terminate a process
$ kill -9 3947
# Find processes using a specific port
$ ss -tlnp | grep 8080
# Restart a service system-wide (distribution-dependent)
$ systemctl restart httpd
# or
$ service apache2 restart
Lab: Process Exploration
# View running processes
$ ps aux | head -n 20
# Find the current shell's PID
$ echo "Shell PID: $$"
# Create a long-running background process and control it
$ sleep 100 &
$ echo "Background sleep started with PID $!"
$ jobs
# Bring it to foreground
$ fg
# Or kill it from another terminal
$ kill -9 $!
Solved example: After sleep 100 &, the shell reports the PID of the background process. jobs shows it as "running" in the background. fg brings it back to the foreground, and the shell waits for the sleep to complete. kill -9 $! forcefully terminates the most recent background process.
Review answers:
- Q: What is the difference between
ps auxandps -ef? A: Both display all processes, butauxshows processes for all users with CPU and memory details, whileefshows a full-format listing. The exact output format varies slightly by implementation. - Q: What signal does
kill PIDsend by default? A: SIGTERM (15), a termination request that the process can catch and handle. - Q: What is a zombie process? A. A child process that has terminated but whose parent has not yet read its exit status via
wait(). It occupies a PID entry but consumes no other resources.
Users and Groups
Linux is a multi-user operating system. Every user has a username, user ID (UID), and belongs to one or more groups. Each group has a group name and group ID (GID).
User management commands
| Command | Description |
|---|---|
useradd |
Add a new user. useradd username creates a new user account with default settings. useradd -m username creates a user and automatically creates their home directory. useradd -s /bin/bash username sets the user's login shell. |
adduser |
Debian/Ubuntu-friendly interactive alternative to useradd. |
userdel |
Delete a user. userdel username removes the user account. userdel -r username removes the user and their home directory. |
passwd |
Change a user's password. Running passwd as root allows changing any user's password. Running passwd as a regular user allows changing their own password. |
usermod |
Modify a user account. usermod -aG groupname username adds the user to a supplementary group without removing them from other groups. usermod -s /bin/zsh username changes the user's login shell. |
su |
Switch to another user. su - username logs in as the specified user (prompts for that user's password). su -c "command" username runs a single command as another user. |
sudo |
Execute a command as the superuser (root). sudo command runs command with root privileges, typically after prompting for the current user's password. Members of the sudo group (or the wheel group on some systems) are allowed to use sudo. |
whoami / id |
Display the current effective user. whoami prints the username. id prints user and group information including UIDs and GIDs. |
Group management commands
| Command | Description |
|---|---|
groupadd |
Add a new group. groupadd groupname creates a new group. |
groupmod |
Modify a group. groupmod -n newgroupname oldgroupname renames a group. |
groupdel |
Delete a group. groupdel groupname removes the group. |
groups |
Display the groups the current user belongs to. groups username shows the groups for a specific user. |
File ownership and access control revisited
When a process attempts to access a file, Linux checks:
- If the process's effective UID matches the file's owner UID → apply owner permissions.
- Else if the process's effective GID or any of its supplementary GIDs matches the file's group GID → apply group permissions.
- Otherwise → apply "other" permissions.
This is why a user might have different access levels to the same file depending on their login context and group memberships.
Lab: User and Group Management
# Add a new user with a home directory and bash shell
$ sudo useradd -m -s /bin/bash student1
# Set the user's password
$ sudo passwd student1
# (Enter and confirm a new password)
# Add the user to the sudo group (note: exact group name may vary)
$ sudo usermod -aG sudo student1
# Verify group membership
$ groups student1
# Switch to the new user
$ su - student1
$ whoami
$ id
# Exit back to root
$ exit
# Create a new group for a project
$ sudo groupadd project-alpha
# Add an existing user to the group
$ sudo usermod -aG project-alpha student1
# Verify the group assignment
$ groups student1
Solved example: After sudo useradd -m -s /bin/bash student1, the user student1 has a home directory at /home/student1 and logs in with /bin/bash. After sudo passwd student1, the user can authenticate with their password. After sudo usermod -aG sudo student1, the user can use sudo to run privileged commands. su - student1 switches to that user, and whoami confirms the effective user.
Review answers:
- Q: What is the difference between
useraddandadduser? A:useraddis a low-level utility;adduseris an interactive, high-level wrapper on Debian/Ubuntu systems that asks for confirmation and sets up the home directory and shell automatically. - Q: How do you add a user to a supplementary group without removing them from other groups? A:
usermod -aG groupname username— the-aflag appends (adds) rather than replaces group memberships. - Q: What does
su - usernamedo differently fromsu username? A:su -simulates a full login, setting up the environment, home directory, and login shell as if the user had logged in from scratch.suwithout-starts a shell in the target user's account but may retain some environment variables from the current session.
Package Management
Package management systems automate the installation, update, and removal of software on Linux systems. The two most common systems are APT (Debian/Ubuntu) and YUM/DNF (RHEL/CentOS/Fedora).
APT (Advanced Package Tool) — Debian/Ubuntu
| Operation | Command | Description |
|---|---|---|
| Update package lists | sudo apt update |
Downloads the package index files from the configured repositories. Updates the local cache of available versions and their dependencies. Do not run this frequently on limited connections; once or twice a day is sufficient. |
| Upgrade installed packages | sudo apt upgrade |
Installs newer versions of all currently installed packages. Requires the package lists to be updated first (apt update). |
| Install a package | sudo apt install package-name |
Downloads and installs the named package along with all required dependencies. If the package is already installed, apt reports that and offers to upgrade. |
| Remove a package | sudo apt remove package-name |
Removes the package's binaries and configuration files, but keeps configuration files on the system for potential reinstallation. |
| Purge a package | sudo apt purge package-name |
Removes the package and all its configuration files. The next reinstallation requires reconfiguring from scratch. |
| Search for a package | apt search term |
Searches package names and descriptions for the given term. Use apt-cache search term as an alternative. |
| Show package information | apt show package-name |
Displays detailed information about an installed or available package, including version, description, dependencies, and maintainer. |
| List installed packages | dpkg -l |
Lists all packages installed on the system, showing package name, version, and architecture. `dpkg -l |
| Held packages | sudo apt-mark hold package-name |
Prevents a package from being automatically upgraded even when a newer version is available in the repositories. sudo apt-unmark package-name releases the hold. |
YUM/DNF — RHEL/CentOS/Fedora
| Operation | Command | Description |
|---|---|---|
| Check for updates | yum check-update or dnf check-update |
Lists available package updates. |
| Update all packages | sudo yum update or sudo dnf update |
Downloads and installs all available updates for installed packages. |
| Install a package | sudo yum install package-name or sudo dnf install package-name |
Downloads and installs the named package and its dependencies. |
| Remove a package | sudo yum remove package-name or sudo dnf remove package-name |
Removes the named package. |
| Search for a package | yum search term or dnf search term |
Searches package names and descriptions. |
| List installed packages | yum list installed or dnf list installed |
Shows all packages installed on the system. |
| List available packages | yum list available or dnf list available |
Shows all packages available in configured repositories. |
Repository configuration
Both APT and YUM/DNF obtain packages from configured software repositories. Repositories are defined in:
- APT:
/etc/apt/sources.listand files in/etc/apt/sources.list.d/ - YUM:
/etc/yum.repos.d/*.repofiles - DNF:
/etc/dnf/repo.d/*.repofiles (compatible with YUM repo files)
A repository URL typically includes the protocol (http:// or https://), the mirror host, the distribution codename (e.g., ubuntu focal, centos stream9), and the component sections (main, universe, contrib, updates, extras).
Lab: Package Management Practice — APT
# Update package lists
$ sudo apt update
# Install the vim text editor
$ sudo apt install vim
# Search for packages related to "web server"
$ apt search apache
# Show information about the nginx package
$ apt show nginx
# Remove a package you no longer need
$ sudo apt remove vim
# Purge the package and its configuration files
$ sudo apt purge vim
# Hold a package to prevent automatic upgrades
$ sudo apt-mark hold linux-image-$(uname -r)
# To release: sudo apt-unmark linux-image-$(uname -r)
Solved example: After sudo apt update, the local package cache is refreshed. sudo apt install vim downloads and installs vim and any required libraries. apt search apache returns a list of packages with "apache" in their name or description. apt show nginx displays nginx's version, description, dependencies, and maintainer. sudo apt-mark hold linux-image-$(uname -r) prevents the current kernel from being auto-upgraded.
Review answers:
- Q: What is the difference between
apt removeandapt purge? A:removeuninstalls the binaries but keeps configuration files;purgeremoves both the binaries and all configuration files. - Q: Which command updates the local package index in APT? A:
apt update. - Q: What does
apt-mark holddo? A: Prevents a specified package from being automatically upgraded, even when a newer version is available in the repositories.
Lab: Package Management Practice — DNF
# Check for available updates
$ sudo dnf check-update
# Install the tree command-line tool
$ sudo dnf install tree
# Search for packages containing "database"
$ dnf search sqlite
# Show detailed info about the httpd package
$ dnf info httpd
# Remove the tree package
$ sudo dnf remove tree
# Check if a specific package is installed
$ dnf list installed tree
# Update the system
$ sudo dnf update -y
Solved example: After sudo dnf check-update, available updates are listed. sudo dnf install tree installs the tree package (which displays directories as a tree structure). dnf search sqlite finds packages related to SQLite. dnf info httpd shows details about the Apache HTTP Server package. sudo dnf remove tree uninstalls the tree package. dnf list installed tree confirms whether tree is installed. sudo dnf update -y updates all installed packages to their latest versions.
Review answers:
- Q: What is the main difference between YUM and DNF? A: DNF is the successor to YUM, offering faster dependency resolution, plug-in support, and better performance. DNF also uses a different plugin system and can communicate with more repository formats.
- Q: Which command removes a package and its configuration files in DNF? A:
dnf remove package-nameremoves the package; configuration files may persist depending on the package. There is no built-in "purge" equivalent, butdnf removetypically cleans up most associated files. - Q: What does
dnf check-updatedo? A: Checks whether any updates are available for installed packages and lists them.
Bash Shell
The Bash (Bourne Again SHell) is the most common shell on Linux systems. It provides a command-line interface for interacting with the operating system, as well as a powerful scripting language.
Bash fundamentals
- Prompt: The default prompt is often
user@host:current_directory$. The prompt can be customized via thePS1environment variable. - Command history: Bash remembers previously entered commands.
Ctrl+P(orUp Arrow) recalls the previous command;Ctrl+Nrecalls the next.historydisplays the command history with line numbers.!nrepeats command numbernfrom the history.!!repeats the last command.Ctrl+Rinitiates an incremental reverse search through the history. - Tab completion: Pressing
Tabauto-completes filenames, command names, and variable names. If there are multiple possibilities, Bash lists them. This works for paths, variable names, and command options. - Aliases: Custom shortcuts for frequently used commands. Defined in
~/.bashrcor~/.bash_aliases. For example:alias ll='ls -la'creates a shortcutllforls -la.alias update='sudo apt update && sudo apt upgrade'creates a single-command system update.
Control structures in Bash scripts
Bash scripts support common programming constructs:
#!/bin/bash
# Variables
NAME="Student"
COURSE="Linux Fundamentals"
# Conditional
if [ "$NAME" = "Student" ]; then
echo "Welcome, $NAME, to $COURSE"
else
echo "Access denied"
fi
# Loops
for i in 1 2 3 4 5; do
echo "Iteration $i"
done
while [ "$i" -le 5 ]; do
echo "While loop: $i"
i=$((i + 1))
done
# Case statement
case "$1" in
start) echo "Starting service" ;;
stop) echo "Stopping service" ;;
restart) echo "Restarting service" ;;
*) echo "Usage: $0 {start|stop|restart}" ;;
esac
Useful one-liners
| One-liner | Purpose |
|---|---|
ls *.txt |
List all .txt files in the current directory. |
find . -name "*.log" -mtime +7 |
Find .log files older than 7 days. |
grep -r "error" /var/log/ |
Search recursively for "error" in /var/log/. |
df -h |
Show disk space usage in human-readable format. |
du -sh * |
Show total size of each item in the current directory (human-readable). |
who |
Show who is currently logged in. |
uptime |
Show how long the system has been running and the current load. |
crontab -e |
Edit the crontab for scheduled task automation. |
Lab: Bash Scripting
#!/bin/bash
# simple.sh — a basic bash script
# Display system information
echo "=== System Information Report ==="
echo "Hostname: $HOSTNAME"
echo "Current user: $(whoami)"
echo "Kernel: $(uname -srm)"
echo "Memory usage:"
free -h
echo "Disk usage:"
df -h
# Check if a file exists
if [ -f "$1" ]; then
echo "File $1 exists and is a regular file."
echo "First 5 lines:"
head -n 5 "$1"
else
echo "File $1 does not exist."
fi
To run: chmod +x simple.sh && ./simple.sh /etc/passwd
Solved example: Running ./simple.sh /etc/passwd prints system information (hostname, current user, kernel version), then checks if /etc/passwd exists. Since it does, it prints a confirmation message and displays the first 5 lines of the file using head. If the file doesn't exist, it prints a not-found message.
Review answers:
- Q: What does
$$represent in a Bash script? A: The PID of the current shell process. - Q: How do you make a Bash script executable? A:
chmod +x scriptname.sh. - Q: What is the purpose of the
-ftest inif [ -f "$1" ]? A: Checks whether the argument is an existing regular file.
Networking
Linux networking fundamentals cover IP addressing, network interfaces, routing, and common network services.
IP addressing
- IPv4: 32-bit addresses written as four decimal octets separated by dots (e.g.,
192.168.1.15). Each octet ranges from 0 to 255. IPv4 addresses are divided into a network portion and a host portion, typically defined by a subnet mask (e.g.,255.255.255.0). - IPv6: 128-bit addresses written as eight groups of four hexadecimal digits separated by colons (e.g.,
2001:db8::1a2b). IPv6 was designed to address the exhaustion of IPv4 addresses and provides improved security and auto-configuration features. - Private IP ranges (IPv4):
10.0.0.0/8— single large network172.16.0.0/12— 16 networks192.168.0.0/16— 256 networks (common in home/office/BCA lab networks)
- Loopback:
127.0.0.1(IPv4) or::1(IPv6) — the address the system uses to refer to itself (localhost).
Network interface commands
| Command | Description |
|---|---|
ifconfig (deprecated) |
Configure network interfaces and display status. Still present on many systems but replaced by ip. |
ip |
The modern replacement for ifconfig. ip addr show displays interface addresses. ip link show shows interface state. ip route show displays the routing table. ip link set dev eth0 up enables an interface. |
ping |
Test connectivity to another host using ICMP echo requests. ping -c 4 8.8.8.8 sends 4 packets to Google's DNS. |
ssh |
Securely connect to a remote host. ssh user@hostname opens an encrypted terminal session. ssh -p 2222 user@hostname connects to a non-default port. |
scp |
Securely copy files between hosts. scp file.txt user@hostname:/path/to/destination/ copies a file. scp -r directory/ user@hostname:/path/to/destination/ copies a directory recursively. |
wget |
Download files from the web. wget http://example.com/file.tar.gz downloads the file. |
curl |
Transfer data from or to a server. curl -O http://example.com/file.tar.gz downloads and saves with the original filename. curl -I http://example.com shows headers only. |
netstat (deprecated) |
Display network connections, routing tables, and interface statistics. Replaced by ss. |
ss |
Socket statistics — a more powerful replacement for netstat. ss -tlnp shows listening TCP connections with process information. |
Routing and name resolution
- Routing table: The kernel's forwarding table that determines where to send packets.
ip route showdisplays the table. Default route (gateway) is typically0.0.0.0/0or::/0. - DNS resolution: Converts hostnames to IP addresses. Configuration in
/etc/resolv.conf. Nameserver entries specify DNS servers to query.nslookup example.comanddig example.comquery DNS and display results.
Lab: Network Exploration
# Show IP addresses and interface status
$ ip addr show
$ ip link show
# Show the routing table
$ ip route show
# Test connectivity
$ ping -c 3 8.8.8.8
# Check DNS configuration
$ cat /etc/resolv.conf
# Find open ports
$ ss -tlnp
# Look up a hostname's IP
$ nslookup www.tu.edu.np
# or
$ dig www.tu.edu.np
# Simple HTTP request
$ curl -I https://www.tu.edu.np
Solved example: ip addr show displays all configured network interfaces with their IP addresses, netmasks, and MTU. ping -c 3 8.8.8.8 sends three ICMP packets to Google's public DNS; if replies are received, the network connection is working. nslookup www.tu.edu.np returns the IP address of the TU website. curl -I https://www.tu.edu.np shows the HTTP headers of the homepage without downloading the body.
Review answers:
- Q: What is the private IPv4 range most commonly used in BCA lab networks? A:
192.168.0.0/16. - Q: What does
pinguse to test connectivity? A: ICMP echo requests and replies. - Q: What command shows the routing table in modern Linux? A:
ip route show.
Security
Linux security encompasses authentication, access control, firewall configuration, and best practices for system hardening.
Authentication and password security
- Password hashing: Passwords are stored as hashes in
/etc/shadow. The hash format typically includes the algorithm, salt, and hashed value. Common algorithms: SHA-512, SHA-256, bcrypt, Argon2. A hash line in/etc/shadowlooks like:$6$<salt>$<hashed-password>, where6indicates SHA-512. - Password strength: Long passphrases with a mix of character types are stronger than short complex passwords. Aim for 12+ characters. Passphrases composed of random words (e.g.,
correct horse battery staple) are both strong and memorable. - Account locking: After several failed login attempts, the account can be temporarily locked. Tools:
fail2banmonitors logs and bans persistent failed-auth attempts.
Firewall with ufw (Uncomplicated Firewall)
ufw is a frontend to iptables designed to be easy to use, especially on Ubuntu/Debian systems.
# Enable ufw
$ sudo ufw enable
# Allow SSH (essential so you don't lock yourself out)
$ sudo ufw allow OpenSSH
# Allow HTTP and HTTPS
$ sudo ufw allow 80/tcp
$ sudo ufw allow 443/tcp
# Check status
$ sudo ufw status
# Deny a specific IP
$ sudo ufw deny from 192.168.1.100
# Reset ufw to defaults
$ sudo ufw reset
SELinux and AppArmor
- SELinux (Security-Enhanced Linux): A Mandatory Access Control (MAC) system integrated into the kernel. It defines strict policies that determine what processes can do, regardless of traditional permission settings. SELinux can be in three modes:
Enforcing(policy is active, violations are blocked),Permissive(policy is logged but not enforced), andDisabled(SELinux is turned off). Default on RHEL/CentOS/Fedora. - AppArmor: Another MAC system that confines individual programs to a set of capabilities. It uses path-based profiles. Default on openSUSE, SUSE Linux Enterprise, and some Ubuntu configurations. Profiles can be
EnforcingorComplaining(logged but not enforced).
Common security practices
- Keep the system updated: Regularly apply security patches with
sudo apt upgrade/sudo dnf update. - Use strong, unique passwords for all accounts, especially root.
- Disable root login via SSH (use
sudoorsuinstead, or authenticate with key-only SSH). - Configure a firewall to allow only necessary services.
- Enable automatic security updates where available.
- Audit user accounts regularly; remove unused accounts.
- Monitor logs in
/var/log/(e.g.,/var/log/auth.log,/var/log/syslog) for suspicious activity. - Use key-based SSH authentication instead of password-only login.
- Restrict sudo access to only necessary users and commands (
sudo visudoto edit the sudoers file). - Encrypt sensitive data at rest and in transit.
Lab: Basic Firewall Setup
# Install and enable ufw (Ubuntu/Debian)
$ sudo apt install ufw
$ sudo ufw enable
# Allow only essential services
$ sudo ufw allow OpenSSH # SSH access
$ sudo ufw allow 80/tcp # HTTP
$ sudo ufw allow 443/tcp # HTTPS
# Deny unnecessary services
$ sudo ufw deny 23/tcp # Telnet (insecure)
$ sudo ufw deny 21/tcp # FTP (insecure; prefer SFTP/SSH)
# Check the firewall status
$ sudo ufw status verbose
# Reset to defaults if you lock yourself out
$ sudo ufw reset
Solved example: After installing and enabling ufw, allowing OpenSSH ensures you can still connect via SSH. Adding HTTP and HTTPS rules allows a web server running on the machine. sudo ufw status verbose shows the current rules and whether the firewall is active. If you accidentally block SSH, sudo ufw reset resets all rules to defaults.
Review answers:
- Q: What is the difference between SELinux and AppArmor? A: SELinux is policy-based and type-enforcing by default, focusing on processes and types of objects; AppArmor is path-based and profile-focused, confining specific programs to designated paths and capabilities.
- Q: What does
ufw enabledo? A: Enables the uncomplicated firewall and activates it immediately. Existing rules (like OpenSSH allow) remain in effect. - Q: Why is it important to allow SSH before enabling the firewall? A: So you don't lock yourself out of the system by blocking your own remote access.
Practical Lab: Comprehensive Linux Lab
This integrated lab exercises the core topics covered in this guide. Complete each step and verify your results.
Lab Setup
Ensure you are in a Linux environment (a virtual machine, lab server, or WSL). Log in as a regular user (not root, unless necessary).
Lab Exercises
Exercise 1: Filesystem Navigation and Permissions
- Create a directory structure:
mkdir -p ~/lab/exercise1/subdir - Create a file
~/lab/exercise1/data.txtwith some sample text. - Set permissions:
chmod 755 ~/lab/exercise1andchmod 644 ~/lab/exercise1/data.txt. - Verify:
ls -l ~/lab/should show the directory asdrwxr-xr-xand the file as-rw-r--r--. - Change to the subdirectory and confirm you can read the file:
cd ~/lab/exercise1 && cat data.txt.
Solved example:
$ mkdir -p ~/lab/exercise1/subdir
$ echo "sample data" > ~/lab/exercise1/data.txt
$ chmod 755 ~/lab/exercise1
$ chmod 644 ~/lab/exercise1/data.txt
$ ls -l ~/lab/
total 8
drwxr-xr-x 2 sushil sushil 4096 Nov 20 15:00 exercise1
-rw-r--r-- 1 sushil sushil 20 Nov 20 15:01 exercise1/data.txt
$ cd ~/lab/exercise1 && cat data.txt
sample data
Review answers:
- Q: What does
chmod 755set for a directory? A: Owner: rwx, Group: r-x, Others: r-x (drwxr-xr-x). - Q: What does
chmod 644set for a file? A: Owner: rw-, Group: r--, Others: r-- (-rw-r--r--). - Q: Can another user read a file with
644permissions if they are not in the owner's group? A: Yes, "others" permission applies to all users who are not the owner or in the file's group.
Exercise 2: Process Management
- Start a long-running background process:
sleep 300 &(this sleeps for 300 seconds, about 5 minutes). - Record the PID:
$!expands to the PID of the most recent background process. - List processes:
ps aux | grep sleepshould show your sleep process. - Terminate the process:
kill $!orkill -9 $!to force-terminate. - Verify the process is gone:
ps aux | grep sleepshould no longer show it (the grep command itself may show up, but the sleep process is gone).
Solved example:
$ sleep 300 &
$ echo "PID: $!"
[1] 3947
$ ps aux | grep sleep
sushil 3947 0.0 0.0 2432 ?? Ss 3:00PM 0:00.01 sleep 300
sushil 4021 0.0 0.0 2416 ?? S+ 3:00PM 0:00.00 grep sleep
$ kill $!
$ ps aux | grep sleep
sushil 4022 0.0 0.0 2416 ?? S+ 3:00PM 0:00.00 grep sleep
(The grep sleep line is normal; the sleep process 3947 is gone.)
Review answers:
- Q: What does
&do after a command? A: Runs the command in the background, returning control to the shell immediately. - Q: What is the difference between
kill PIDandkill -9 PID? A:kill PIDsends SIGTERM (termination request, the process can clean up);kill -9 PIDsends SIGKILL (immediate, cannot be caught or ignored). - Q: What is a zombie process? A: A terminated child process whose parent has not yet read its exit status via
wait(). It occupies a PID entry but no other resources.
Exercise 3: Package Management
- Update package lists:
sudo apt update(orsudo dnf check-updateon Fedora). - Install
treeif not already installed:sudo apt install tree(orsudo dnf install tree). - Verify installation:
tree --versionshould print the version string. - Use
treeto display the structure of your home directory:tree ~(ortree ~/lab). - Remove the package:
sudo apt remove tree(orsudo dnf remove tree). - Confirm removal:
dpkg -l | grep tree(ordnf list installed | grep tree) should show the package as removed.
Solved example:
$ sudo apt update
... (output showing package index updates)
$ sudo apt install tree
... (downloading and installing tree)
$ tree --version
tree v1.8.0
$ tree ~/lab
~/lab
├── exercise1
│ ├── data.txt
│ └── subdir
└── exercise2.sh
$ sudo apt remove tree
$ dpkg -l | grep tree
(no output or "no packages found matching tree")
Review answers:
- Q: What is the difference between
apt removeandapt purge? A:removeuninstalls the binaries;purgeuninstalls binaries and removes configuration files. - Q: Which command lists installed packages in dpkg format? A:
dpkg -l. - Q: What does
treedo? A: Displays directories and files as a tree structure, visualizing the hierarchy.
Exercise 4: Bash Scripting
- Create a script
~/lab/report.shwith the following content:
#!/bin/bash
echo "System Report"
echo "==========="
echo "Hostname: $HOSTNAME"
echo "User: $(whoami)"
echo "Kernel: $(uname -r)"
echo "Memory:"
free -h
echo "Disk:"
df -h
- Make it executable:
chmod +x ~/lab/report.sh. - Run it:
~/lab/report.sh. - Modify the script to accept a filename argument and display the first 3 lines: add
if [ -f "$1" ]; then echo "File exists:"; head -n 3 "$1"; fito the script, then run~/lab/report.sh /etc/passwd.
Solved example:
#!/bin/bash
echo "System Report"
echo "==========="
echo "Hostname: $HOSTNAME"
echo "User: $(whoami)"
echo "Kernel: $(uname -r)"
echo "Memory:"
free -h
echo "Disk:"
df -h
After chmod +x and ~/lab/report.sh, the output shows hostname, user, kernel version, memory usage, and disk usage. Adding the argument handling and running ~/lab/report.sh /etc/passwd additionally prints "File exists:" followed by the first 3 lines of /etc/passwd.
Review answers:
- Q: What is the shebang line and what does it do? A:
#!/bin/bashat the top of a script tells the system to use Bash to interpret the script. - Q: How do you pass arguments to a Bash script? A: Arguments are accessed via
$1(first),$2(second), etc.$0is the script name. - Q: What does
free -hdisplay? A: Memory usage in human-readable format (shows total, used, free, shared, buff/cache, and available memory).
Exercise 5: Networking
- Show your IP configuration:
ip addr show— note your inet address and netmask. - Ping the default gateway (often
192.168.1.1or10.0.0.1— useip route showto find it):ping -c 3 <gateway-ip>. - Look up a DNS hostname:
nslookup www.google.comordig www.google.com. - Check open listening ports:
ss -tlnp.
Solved example:
$ ip addr show
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
inet 192.168.1.15/24 brd 192.168.1.255 scope global eth0
...
$ ip route show
default via 192.168.1.1 dev eth0
After ping -c 3 192.168.1.1, you should see three replies if the gateway is reachable. nslookup www.google.com returns the IP address of www.google.com. ss -tlnp shows listening TCP ports and associated PIDs.
Review answers:
- Q: What does
ip addr showdisplay? A: IP addresses and configuration for all network interfaces. - Q: How do you find the default gateway? A:
ip route showdisplays the routing table; the default route line (e.g.,default via 192.168.1.1) shows the gateway. - Q: What is the difference between
nslookupanddig? A: Both query DNS;dig(Domain Information Groper) provides more detailed output and is more flexible;nslookup(name server lookup) is simpler and older, but both resolve hostnames to IP addresses.
Review Answers Summary
Linux Architecture
- Q: What is the top-level directory in the Linux filesystem hierarchy? A:
/ - Q: Which directory holds system configuration files? A:
/etc - Q: What does the
/procfilesystem provide? A: Virtual filesystem exposing process and kernel information
Commands and Files
- Q: What does
ls -ashow thatlsdoes not? A: Hidden files (files whose names start with.) - Q: What is the difference between
rm fileandrm -r directory? A:rm filedeletes a single file;rm -r directoryremoves a directory and all its contents recursively. - Q: What does
head -5 file.txtdo? A: Displays the first 5 lines offile.txt
Permissions
- Q: What does
chmod 644 fileset? A: Owner can read and write; group and others can read only. - Q: In the symbol string
-rwxr-xr-x, what does the firstrwxrepresent? A: Owner permissions (read, write, execute). - Q: What is the sticky bit used for on the
/tmpdirectory? A: Allows any user to create files in/tmp, but only the file's owner, the directory's owner, or root can delete or rename those files.
Processes
- Q: What is the difference between
ps auxandps -ef? A: Both display all processes, butauxshows processes for all users with CPU and memory details, whileefshows a full-format listing. - Q: What signal does
kill PIDsend by default? A: SIGTERM (15), a termination request that the process can catch and handle. - Q: What is a zombie process? A. A child process that has terminated but whose parent has not yet read its exit status via
wait().
Users and Groups
- Q: What is the difference between
useraddandadduser? A:useraddis a low-level utility;adduseris an interactive, high-level wrapper on Debian/Ubuntu systems. - Q: How do you add a user to a supplementary group without removing them from other groups? A:
usermod -aG groupname username— the-aflag appends (adds) rather than replaces group memberships. - Q: What does
su - usernamedo differently fromsu username? A:su -simulates a full login, setting up the environment, home directory, and login shell as if the user had logged in from scratch.
Package Management
- Q: What is the difference between
apt removeandapt purge? A:removeuninstalls the binaries but keeps configuration files;purgeremoves both the binaries and all configuration files. - Q: Which command updates the local package index in APT? A:
apt update. - Q: What does
apt-mark holddo? A: Prevents a specified package from being automatically upgraded, even when a newer version is available in the repositories.
Bash Shell
- Q: What does
$$represent in a Bash script? A: The PID of the current shell process. - Q: How do you make a Bash script executable? A:
chmod +x scriptname.sh. - Q: What is the purpose of the
-ftest inif [ -f "$1" ]? A: Checks whether the argument is an existing regular file.
Networking
- Q: What is the private IPv4 range most commonly used in BCA lab networks? A:
192.168.0.0/16. - Q: What does
pinguse to test connectivity? A: ICMP echo requests and replies. - Q: What command shows the routing table in modern Linux? A:
ip route show.
Security
- Q: What is the difference between SELinux and AppArmor? A: SELinux is policy-based and type-enforcing by default, focusing on processes and types of objects; AppArmor is path-based and profile-focused, confining specific programs to designated paths and capabilities.
- Q: What does
ufw enabledo? A: Enables the uncomplicated firewall and activates it immediately. Existing rules (like OpenSSH allow) remain in effect. - Q: Why is it important to allow SSH before enabling the firewall? A: So you don't lock yourself out of the system by blocking your own remote access.
Conclusion
This supplemental study guide covers the essential Linux topics expected in a BCA Semester-7 course: Linux architecture, command-line operations, file permissions, process management, user and group administration, package management, Bash scripting, networking fundamentals, and security best practices. Each section provides conceptual foundations, practical command examples, and review questions with answers to reinforce learning.
Remember that this guide is not the official Tribhuvan University micro-syllabus. The TU 2025 course structure lists BCA404-IV Linux, Semester 7, 3 credits, but publishes no numbered unit outline. All material here is original BCA Nepal content created to support your learning journey. Use it as a study companion, a lab reference, and a preparation resource — but always verify against official course materials and instructor guidance.
Continue practicing the labs, explore commands in a safe environment, and build your confidence with the Linux operating system. Mastery of the command line and system administration fundamentals will serve you well in your career as a computer application professional, whether you're working on servers, development environments, or embedded systems.
Word count check: The content above is approximately 1800 words. Let me verify this by counting more precisely.