0% found this document useful (0 votes)
11 views106 pages

Linux Notes

Linux is an open-source, Unix-like operating system kernel developed by Linus Torvalds, known for its customization, security, and use in various environments. It is favored for DevSecOps due to its flexibility, robust security features, and extensive tooling support. The document also covers Linux architecture, popular distributions, and compares Linux with Windows and macOS.

Uploaded by

Yashraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views106 pages

Linux Notes

Linux is an open-source, Unix-like operating system kernel developed by Linus Torvalds, known for its customization, security, and use in various environments. It is favored for DevSecOps due to its flexibility, robust security features, and extensive tooling support. The document also covers Linux architecture, popular distributions, and compares Linux with Windows and macOS.

Uploaded by

Yashraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

Linux Notes

1. What is Linux?
Linux is an open-source, Unix-like operating system kernel originally developed by Linus
Torvalds in 1991. It is the core of many operating systems known as Linux distributions (or
distros). Linux is highly customizable, secure, and widely used in servers, desktops, and
embedded systems.

Key Characteristics

a
●​ Open-Source: The source code is freely available, allowing users to modify and

ry
distribute it.
●​ Multi-user and Multitasking: Supports multiple users and processes
simultaneously.
●​ Modular Design: Uses a kernel with modules for hardware and software integration.
su
●​ Community-Driven: Developed and maintained by a global community of
contributors.

Why Linux?
ith
●​ Free to use and distribute.
●​ Highly stable and reliable for long-running systems.
●​ Extensive support for programming and development tools.
w

2. Why Use Linux for DevSecOps?


ev

DevSecOps (Development, Security, Operations) is a practice that integrates security into


the software development and operations lifecycle. Linux is a preferred choice for
DevSecOps due to its flexibility, security, and compatibility with modern tools.
D

Reasons to Use Linux for DevSecOps

1.​ Open-Source Nature:


○​ Allows customization of tools and scripts for automation.
○​ No licensing costs, making it cost-effective for large-scale deployments.
2.​ Security Features:
○​ Robust permission models (e.g., file permissions, user roles).
○​ Built-in tools like SELinux and AppArmor for enhanced security.
○​ Regular security updates from the community.
3.​ Tooling Support:
○​ Native support for DevSecOps tools like Docker, Kubernetes, Jenkins, and
Ansible.
○​ Command-line interface (CLI) for scripting and automation.
4.​ Scalability:
○​ Ideal for cloud environments (e.g., AWS, Azure) and containerized workloads.
○​ Lightweight distributions optimize resource usage.
5.​ Community and Ecosystem:
○​ Large community support for troubleshooting and tool development.
○​ Compatible with CI/CD pipelines and infrastructure-as-code frameworks.

Example Use Case

In a DevSecOps pipeline, Linux servers can host Jenkins for CI/CD, run Docker containers

a
for microservices, and use tools like Trivy for vulnerability scanning, all managed via Bash
scripts or Ansible playbooks.

ry
3. Linux Architecture
su
The Linux architecture is a layered structure that enables efficient interaction between
hardware and software. It is composed of several key components: Applications, Shell,
Kernel, and Hardware. Below is a detailed explanation of each component.
ith
3.1 Hardware

The hardware layer consists of the physical components of a computer system, such as:
w

●​ CPU: Processes instructions and performs computations.


●​ RAM: Temporary storage for running processes.
●​ Storage Devices: Hard drives (HDD), SSDs, or NVMe for data storage.
ev

●​ Peripherals: Input/output devices like keyboards, mice, and network cards.


●​ Role in Linux: The kernel communicates directly with hardware through device
drivers, abstracting hardware complexities for higher layers.

Example: A Linux system uses device drivers to manage a network card for internet
D

connectivity.

3.2 Kernel

The kernel is the core of the Linux operating system, acting as a bridge between hardware
and software. It manages system resources and provides essential services.

Key Functions

●​ Process Management: Handles process creation, scheduling, and termination.


●​ Memory Management: Allocates and deallocates memory for processes.
●​ Device Management: Communicates with hardware via drivers.
●​ File System Management: Manages file operations (e.g., read, write).
●​ Inter-Process Communication: Enables processes to communicate (e.g., pipes,
sockets).

Types of Kernel

●​ Monolithic Kernel: Linux uses a monolithic kernel with modular components


(loadable kernel modules) for flexibility.
●​ Modules: Dynamically loadable drivers (e.g., for USB devices) that can be added or
removed without rebooting.

Example: To view kernel modules:

lsmod

a
ry
3.3 Shell

The shell is a command-line interface (CLI) that allows users to interact with the kernel and
run commands or scripts. It interprets user inputs and communicates them to the kernel.
su
Types of Shells

●​ Bash (Bourne Again Shell): Default shell in most Linux distributions.


●​ Zsh: Advanced shell with enhanced features like auto-completion.
ith
●​ Fish: User-friendly with syntax highlighting.
●​ Others: Tcsh, Ksh, etc.

Key Features
w

●​ Command Execution: Runs commands like ls, cp, or grep.


●​ Scripting: Supports automation via shell scripts.
●​ Piping and Redirection: Combines commands (e.g., ls | grep txt) or redirects
ev

output (e.g., ls > output.txt).

Example: To create a file using the shell:


D

touch myfile.txt

3.4 Applications

Applications are user-level programs that run on top of the shell and kernel. They provide
functionality for end-users, such as web browsers, text editors, or DevSecOps tools.

Types of Applications

●​ System Utilities: Tools like ls, cat, chmod for system management.
●​ Graphical Applications: Browsers (e.g., Firefox), IDEs (e.g., VS Code).
●​ DevSecOps Tools: Docker, Kubernetes, Jenkins for development and operations.
●​ Custom Applications: User-developed programs in languages like Python, C++, or
Java.

Role in Linux

●​ Applications interact with the kernel through system calls, facilitated by system
libraries (e.g., glibc).
●​ They can be installed via package managers (e.g., apt, yum) or compiled from
source.

Example: Install a text editor like nano on Ubuntu:

a
sudo apt install nano

ry
Interaction Between Components

●​ Hardware to Kernel: The kernel uses drivers to manage hardware resources.


su
●​ Kernel to Shell: The shell sends user commands to the kernel via system calls.
●​ Shell to Applications: Applications are launched and managed through shell
commands.
●​ Applications to User: Users interact with applications via graphical interfaces or the
shell.
ith
Example Workflow:

1.​ A user runs ls in the Bash shell.


2.​ The shell sends the command to the kernel.
w

3.​ The kernel accesses the file system on the hardware.


4.​ The kernel returns the file list, displayed by the shell.
ev

4. Linux Flavours
D

Linux flavours, or distributions, are operating systems built around the Linux kernel, tailored
for specific use cases. Each distro combines the kernel with different software, package
managers, and configurations.

Popular Linux Flavours

1.​ Ubuntu:
○​ User-friendly, widely used for desktops and servers.
○​ Package manager: APT (uses .deb packages).
○​ Ideal for beginners and DevSecOps (e.g., supports Docker, Kubernetes).
2.​ Debian:
○​ Stable and reliable, used for servers.
○​ Package manager: APT.
○​ Basis for Ubuntu.
3.​ Fedora:
○​ Cutting-edge features, backed by Red Hat.
○​ Package manager: DNF (uses .rpm packages).
○​ Suited for developers and testing new technologies.
4.​ CentOS Stream / Rocky Linux:
○​ Enterprise-focused, compatible with Red Hat Enterprise Linux (RHEL).
○​ Package manager: YUM/DNF.
○​ Common in production servers.
5.​ Arch Linux:
○​ Minimal and highly customizable.
○​ Package manager: Pacman.

a
○​ Preferred by advanced users.
6.​ Kali Linux:

ry
○​ Designed for security professionals and penetration testing.
○​ Pre-installed with security tools like Metasploit, Nmap.

Choosing a Flavour
su
●​ For DevSecOps: Ubuntu or CentOS for stability and tool support.
●​ For learning: Ubuntu or Fedora for ease of use.
●​ For security: Kali Linux for penetration testing.
ith

5. What is Unix?
w

Unix is an operating system developed in the 1970s at Bell Labs by Ken Thompson, Dennis
Ritchie, and others. It is a multitasking, multi-user system known for its stability and
portability.
ev

Key Features of Unix

●​ Modular design with simple, single-purpose tools.


D

●​ Hierarchical file system (inspired Linux’s file system).


●​ Emphasis on text-based processing and scripting.
●​ Used in enterprise environments (e.g., Solaris, AIX).

Modern Unix Systems

●​ Commercial: Solaris, AIX, HP-UX.


●​ Open-Source: FreeBSD, OpenBSD (Unix-like systems).

6. Difference Between Windows, Linux, and macOS


Feature Windows Linux macOS

Type Proprietary OS Open-source OS Proprietary Unix-like


OS

Kernel Windows NT Linux (Monolithic) XNU (Hybrid,


(Hybrid) Unix-based)

Cost Paid (license Free (most distros) Free with Apple


required) hardware

Customization Limited Highly customizable Moderate (limited by


Apple)

a
File System NTFS, FAT32 ext4, Btrfs, XFS APFS, HFS+

Command Line PowerShell, CMD Bash, Zsh, etc. Bash, Zsh (Terminal)

ry
Security Vulnerable to Strong Secure (Unix-based,
malware (permission-based) Gatekeeper)
su
Use Case

Software
General-purpose,
gaming

Wide (e.g., MS
Servers, DevSecOps,
development

Open-source tools,
Creative work, Apple
ecosystem

Apple-specific apps,
Support Office, games) DevSecOps some Unix
ith
Hardware Runs on diverse Runs on diverse Apple hardware only
hardware hardware
w

Key Differences

●​ Windows: User-friendly, proprietary, widely used for desktops and gaming. Less
ev

suited for DevSecOps due to licensing and limited CLI.


●​ Linux: Open-source, highly customizable, ideal for servers, cloud, and DevSecOps.
Steeper learning curve for beginners.
●​ macOS: Unix-based, proprietary, optimized for Apple hardware. Good for
development but less flexible than Linux.
D

Ubuntu File System


File System Structure

1. Root Directory (/)

●​ The root directory (/) is the top-level directory in Ubuntu’s file system.
●​ All other directories, such as /bin, /home, and /etc, are located under /.
●​ It serves as the foundation for the entire file system hierarchy.

Example: To navigate to the root directory and list its contents:

cd /

ls

Sample Output:

bin boot dev etc home lib media mnt opt proc root run sbin srv sys tmp usr var

a
2. Binary Directory (/bin)

ry
●​ The /bin directory stores essential binary files (executable commands) used by all
users, including the root user.
su
●​ These are critical system commands available even in single-user mode.
●​ Examples of binaries: ls, cp, mv, cat, bash.

Example: To check the binary files in /bin:


ith
cd /bin

ls
w

Sample Output:
ev

bash cat chmod cp date df dir echo grep ls mkdir mv rm touch

Note: Additional user-installed binaries may reside in /usr/bin, and system administration
D

binaries (e.g., fdisk) are in /sbin.

3. Home Directory (/home)

●​ The /home directory contains home directories for all users (except the root user,
whose home is /root).
●​ In Ubuntu, the default user (e.g., ubuntu) has a home directory at /home/ubuntu.
●​ When you create a new user, their directory is automatically created under /home
(e.g., /home/newuser).

Example: To check the default user’s home directory:


cd /home/ubuntu

ls

Creating a New User:

●​ To create a new user newuser:

sudo adduser newuser

●​ This creates /home/newuser with default subdirectories.

a
4. Configuration Directory (/etc)

ry
●​ The /etc directory stores system-wide configuration files.
●​ Examples:
○​ /etc/passwd: Contains user account information.
su ○​ /etc/apt/sources.list: Lists software sources for the apt package
manager.

Example: To view the package sources:


ith
cat /etc/apt/sources.list

Exploring Binary Files


w

To check where binary files are stored in Ubuntu, you can navigate to the /bin directory
ev

using the following commands:

cd /

ls
D

cd bin

ls

●​ Step 1: cd / takes you to the root directory.


●​ Step 2: ls lists directories like bin, home, etc.
●​ Step 3: cd bin moves you to the /bin directory.
●​ Step 4: ls lists binary files like bash, ls, cp.
Practice Commands
1.​ List all directories under root:

cd /

ls

2.​ Explore binaries in /bin:

cd /bin

a
ls

ry
3.​ Check your home directory:

su
cd /home/ubuntu

ls
ith
4.​ Create a new user and verify their home directory:

sudo adduser testuser


w

ls /home​


ev

Ubuntu Commands
1. System Information Commands
D

1.1 Check Operating System

To identify the operating system and its version in Ubuntu, use the lsb_release command.

Command:

lsb_release -a

Description:
●​ Displays detailed information about the Ubuntu version, including release number,
codename, and description.
●​ LSB stands for Linux Standard Base.

Example:

lsb_release -a

Sample Output:

No LSB modules are available.

a
Distributor ID: Ubuntu

Description: Ubuntu 24.04 LTS

ry
Release: 24.04

Codename:
su noble

Note: Ubuntu releases updates in April (e.g., 24.04) and October (e.g., 24.10). LTS versions
(e.g., 22.04, 24.04) are released every two years in April and supported for five years, ideal
ith
for stability in production environments.

1.2 Check Current Date and Time


w

To display the system’s date and time, use the date command.

Command:
ev

date
D

Description:

●​ Shows the current date and time based on the system clock.

Example:

date

Sample Output:

Tue May 20 12:52:13 IST 2025


Additional Tip:

●​ To set the date (requires sudo):

sudo date -s "2025-05-20 12:55:00"

1.3 Check Current User

To identify the current user, use the whoami command.

a
Command:

ry
whoami

su
Description:

●​ Displays the username of the current logged-in user.

Example:
ith
whoami
w

Sample Output:

ubuntu
ev

Note: In Ubuntu, the default user is often ubuntu for cloud or server installations.
D

2. File and Directory Operations


2.1 Echo Command

The echo command displays text or variables in the terminal.

Command:

echo [text or variable]


Description:

●​ Useful for printing messages or environment variables.


●​ Common variable: echo $HOME shows the user’s home directory.

Example:

echo "Hello, Ubuntu!"

echo $HOME

Sample Output:

a
Hello, Ubuntu!

ry
/home/ubuntu

su
2.2 Change Directory (cd)

The cd command navigates between directories.


ith
Command:

cd [directory]
w

Description:
ev

●​ Changes the current working directory.


●​ Common options:
○​ cd ..: Move one directory up (parent directory).
○​ cd ../..: Move two directories up.
○​ cd /: Go to the root directory.
D

○​ cd ~ or cd: Go to the user’s home directory (e.g., /home/ubuntu).

Examples:

1.​ Go to the root directory:

cd /

2.​ Go to the home directory:


cd /home/ubuntu

3.​ Navigate to a specific directory (e.g., /home/ubuntu/Boys):

cd /home/ubuntu/Boys

4.​ Move up one directory:

cd ..

a
5.​ Move up two directories:

ry
cd ../..

su
2.3 List Directory Contents (ls)

The ls command lists files and directories.


ith
Command:

ls
w

ls -l
ev

Description:

●​ ls: Lists files and directories in the current directory.


●​ ls -l: Lists in long format, showing permissions, owner, size, and modification time.
D

○​ If the first character is d, it’s a directory.


○​ If the first character is -, it’s a file.

Example:

ls

ls -l

Sample Output:
# ls

Boys file1.txt file2.txt

# ls -l

drwxr-xr-x 2 ubuntu ubuntu 4096 May 20 12:50 Boys

-rw-r--r-- 1 ubuntu ubuntu 0 May 20 12:45 file1.txt

-rw-r--r-- 1 ubuntu ubuntu 0 May 20 12:45 file2.txt

a
●​ drwxr-xr-x: Indicates Boys is a directory (d).

ry
●​ -rw-r--r--: Indicates file1.txt and file2.txt are files (-).

2.4 Create Files (touch)


su
The touch command creates empty files or updates their timestamps.

Command:
ith
touch [filename]

Description:
w

●​ Creates one or more empty files.


●​ Supports brace expansion for creating multiple files (e.g., file{1..5}.txt).
ev

Examples:

1.​ Create a single file:


D

touch file.txt

2.​ Create multiple files (e.g., file1.txt to file5.txt):

touch file{1..5}.txt

ls

Sample Output:
file1.txt file2.txt file3.txt file4.txt file5.txt

2.5 Create Directories (mkdir)

The mkdir command creates directories.

Command:

mkdir [directory_name]

a
Description:

ry
●​ Creates one or more directories.
●​ Supports brace expansion for multiple directories (e.g., day{0..10}).
●​ Use -p to create parent and child directories together.
su
Examples:

1.​ Create a single directory:

mkdir suryamani
ith
mkdir Boys
w

2.​ Create multiple directories:

mkdir day{0..10}
ev

ls
D

Sample Output:

day0 day1 day2 day3 day4 day5 day6 day7 day8 day9 day10

3.​ Create parent and child directories:

mkdir -p parent/child

ls parent
Sample Output:

child

2.6 Move or Rename Files/Directories (mv)

The mv command moves or renames files and directories.

Command:

mv [source] [destination]

a
ry
Description:

●​ Moves files or directories to another location.


●​ Also used to rename files or directories (by specifying a new name in the same
su
directory).
●​ No need for -r (recursive) as mv handles directories by default.

Examples:
ith
1.​ Move a directory (suryamani) into another directory (Boys):

mkdir suryamani

mkdir Boys
w

mv suryamani Boys
ev

cd Boys

ls
D

Sample Output:

suryamani

2.​ Navigate to Boys and verify:

cd Boys

ls
Sample Output:

suryamani

3.​ Rename a directory (e.g., suryamani to newname):

mv Boys/suryamani Boys/newname

ls Boys

a
Sample Output:

ry
newname

su
2.7 Delete Files and Directories (rm)

The rm command removes files or directories.


ith
Command:

rm [file]
w

rm -r [directory]
ev

Description:

●​ rm [file]: Deletes a single file.


●​ rm -r [directory]: Deletes a directory and its contents recursively (-r stands
D

for recursive).
●​ Use -f (force) to avoid confirmation prompts (e.g., rm -rf).

Examples:

1.​ Delete a file:

touch file.txt

rm file.txt

ls
2.​ Delete a directory and its contents:

mkdir Boys

rm -r Boys

ls

Note: Be cautious with rm -r as it permanently deletes without moving to a trash bin.

a
2.8 View Command History

ry
The history command displays previously executed commands.

Command:

historysu
Description:
ith
●​ Shows a numbered list of commands run in the current session.
●​ Useful for recalling and reusing commands.

Example:
w

history
ev

Sample Output:

1 lsb_release -a
D

2 date

3 whoami

4 touch file1.txt

5 ls -l

Tip:
●​ Run a specific command from history using its number:

!3

This runs whoami (command number 3 in the example).

Practice Workflow
To practice the commands in Ubuntu:

1.​ Check your OS:

a
lsb_release -a

ry
2.​ Create directories and move one into another:
su
mkdir suryamani Boys

mv suryamani Boys

cd Boys
ith
ls
w

3.​ Navigate back:

cd ..
ev

4.​ Create multiple files and directories:


D

touch file{1..5}.txt

mkdir day{0..10}

ls

5.​ Create a parent-child directory structure:

mkdir -p parent/child
6.​ Delete a file and directory:

rm file1.txt

rm -r Boys

7.​ Check command history:

history

Ubuntu User Management

a
ry
1. User Creation
1.1 Create a User
su
To create a new user in Ubuntu, use the useradd command with the -m option to create a
home directory.

Command:
ith
sudo useradd -m [username]
w

Description:

●​ -m: Creates a home directory for the user (e.g., /home/suryamani).


ev

●​ Requires sudo as user creation is an administrative task.


●​ Without sudo, you’ll get a “permission denied” error.

Example:
D

sudo useradd -m suryamani

ls /home

Sample Output:

suryamani ubuntu

Note:
●​ The new user’s home directory (/home/suryamani) contains default subdirectories
like Documents, Downloads, etc.
●​ To set a shell (e.g., Bash), add -s /bin/bash:

sudo useradd -m -s /bin/bash suryamani

1.2 Set a Password for a User

To set or change a user’s password, use the passwd command.

Command:

a
sudo passwd [username]

ry
Description:
su
●​ Prompts for a new password for the specified user.
●​ Requires sudo for administrative access.

Example:
ith
sudo passwd suryamani
w

Prompt:

Enter new UNIX password:


ev

Retype new UNIX password:

Output:
D

passwd: password updated successfully

Note:

●​ Use strong passwords (e.g., mix of letters, numbers, symbols).


●​ To set passwords for multiple users, run passwd separately for each:

sudo passwd surya


sudo passwd abhishek

2. File Viewing and Editing

2.1 View File Contents (cat)

The cat command displays the contents of a file.

Command:

a
cat [filename]

ry
Description:

●​ Outputs the entire content of a file to the terminal.


su
●​ Useful for small text files.

Example:

echo "Hello, Ubuntu!" > file.txt


ith
cat file.txt
w

Sample Output:

Hello, Ubuntu!
ev

2.2 Edit Files with vim


D

The vim command is a powerful text editor for editing files in the terminal.

Command:

vim [filename]

Description:

●​ Opens the file in Vim editor.


●​ Key modes:
○​ Normal Mode: Default mode for navigation (use arrow keys).
○​ Insert Mode: Enter i to start editing.
○​ Command Mode: Press Esc, then type :wq to save and quit, or :q! to quit
without saving.

Example:

1.​ Create and edit a file:

vim file.txt

2.​ Press i to enter insert mode.

a
3.​ Type text (e.g., “This is a test file.”).
4.​ Press Esc to return to normal mode.

ry
5.​ Type :wq and press Enter to save and quit.
6.​ Verify the content:

su
cat file.txt

Sample Output:
ith
This is a test file.
w

Common Vim Commands:

●​ :w – Save the file.


●​ :q – Quit Vim.
ev

●​ :q! – Quit without saving.


●​ dd – Delete a line (in normal mode).
●​ u – Undo changes.
D

Note:

●​ If you get stuck, press Esc and type :q! to exit without changes.
●​ Install Vim if not present:

sudo apt update

sudo apt install vim

2.3 View First Few Lines (head)


The head command displays the first few lines of a file.

Command:

head -n [number] [filename]

Description:

●​ -n [number]: Specifies the number of lines to display (default is 10).

Example:

a
echo -e "Line 1\nLine 2\nLine 3\nLine 4" > file.txt

head -n 3 file.txt

ry
Sample Output:
su
Line 1

Line 2
ith
Line 3
w

2.4 View Last Few Lines (tail)

The tail command displays the last few lines of a file.


ev

Command:

tail -n [number] [filename]


D

Description:

●​ -n [number]: Specifies the number of lines to display (default is 10).

Example:

tail -n 2 file.txt

Sample Output:
Line 3

Line 4

3. User and Group Information


3.1 View All Users

To list all users on the system, view the /etc/passwd file.

Command:

cat /etc/passwd

a
ry
Description:

●​ /etc/passwd contains user account information.


su
●​ Each line represents a user, with fields separated by ::
○​ Username, password placeholder, UID, GID, user info, home directory, shell.

Example:
ith
cat /etc/passwd

Sample Output:
w

root:x:0:0:root:/root:/bin/bash
ev

ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash

suryamani:x:1001:1001::/home/suryamani:/bin/bash
D

Explanation:

●​ suryamani:x:1001:1001::/home/suryamani:/bin/bash:
○​ Username: suryamani
○​ Password: x (stored in /etc/shadow)
○​ UID: 1001
○​ GID: 1001
○​ Home: /home/suryamani
○​ Shell: /bin/bash
3.2 View All Groups

To list all groups, view the /etc/group file.

Command:

sudo cat /etc/group

Description:

●​ /etc/group contains group information.


●​ Each line includes group name, password placeholder, GID, and members.

a
Example:

ry
sudo cat /etc/group

su
Sample Output:

DevSecOps:x:1002:
ith
Developer:x:1003:suryamani

4. Group Management
w

4.1 Create a Group


ev

To create a new group, use the groupadd command.

Command:
D

sudo groupadd [groupname]

Description:

●​ Creates a new group with a unique GID.


●​ Requires sudo as it’s an administrative task.

Examples:

1.​ Create a group DevSecOps:


sudo groupadd DevSecOps

2.​ Create a group Developer:

sudo groupadd Developer

3.​ Verify groups:

sudo cat /etc/group

a
Sample Output:

ry
DevSecOps:x:1002:

Developer:x:1003:
su
4.2 Add User to a Group
ith
To add a user to a group, use the usermod command with -aG.

Command:
w

sudo usermod -aG [groupname] [username]


ev

Description:

●​ -aG: Adds the user to the specified group (-a ensures appending, not overwriting).
●​ Requires sudo.
D

Example:

sudo usermod -aG DevSecOps suryamani

sudo cat /etc/group

Sample Output:

DevSecOps:x:1002:suryamani
Note:

●​ Without -a, usermod -G replaces all existing group memberships.


●​ Verify user’s groups:

groups suryamani

5. Additional User Management Commands

a
5.1 Delete a User

ry
To delete a user, use the userdel command.

Command:

su
sudo userdel -r [username]

Description:
ith
●​ -r: Deletes the user’s home directory and mail spool.
●​ Requires sudo.

Example:
w

sudo userdel -r suryamani


ev

ls /home

Sample Output:
D

ubuntu

5.2 Delete a Group

To delete a group, use the groupdel command.

Command:

sudo groupdel [groupname]


Example:

sudo groupdel DevSecOps

sudo cat /etc/group

Note:

●​ Ensure no users are assigned to the group before deletion.

a
Practice Workflow

ry
1.​ Create a user and set their password:

sudo useradd -m suryamani


su
sudo passwd suryamani

2.​ Create groups and add the user:


ith
sudo groupadd DevSecOps

sudo groupadd Developer


w

sudo usermod -aG DevSecOps suryamani

sudo cat /etc/group


ev

3.​ Create and edit a file:


D

touch file.txt

vim file.txt

# Inside vim: press i, type "Test content", press Esc, type :wq

cat file.txt

4.​ View specific lines:

head -n 3 file.txt
tail -n 2 file.txt

5.​ List all users and groups:

cat /etc/passwd

sudo cat /etc/group

6.​ Clean up:

a
sudo userdel -r suryamani

sudo groupdel DevSecOps

ry
sudo groupdel Developer

su
Additional Notes
●​ Permission Denied: Always use sudo for administrative commands (e.g., useradd,
ith
groupadd) to avoid “permission denied” errors.
●​ Password Security: Use strong passwords and store them securely.
●​ Vim Tips:
○​ Practice switching between modes (insert, normal, command).
w

○​ Use :q! to exit without saving if you make a mistake.


●​ File Safety:
○​ Double-check before deleting users or groups to avoid data loss.
ev

○​ Backup important files before editing with vim.


●​ Man Pages: Use man [command] for detailed help (e.g., man useradd).

Ubuntu User Management and Jump


D

Server (RSA)
1. User Management
1.1 Primary and Secondary Groups
When you create a user in Ubuntu, a primary group with the same name as the user is
automatically created. Users can also be added to secondary groups for additional
permissions.

●​ Primary Group:
○​ Assigned to a user at creation, used as the default group for files created by
the user.
○​ Stored in /etc/passwd (GID field) and /etc/group.
●​ Secondary Group:
○​ Additional groups a user can belong to for shared access to resources.
○​ Added using usermod -aG.

Example:

a
1.​ Create a user suryamani:

ry
sudo useradd -m suryamani

sudo passwd suryamani


su
2.​ Check the primary group in /etc/passwd:
ith
cat /etc/passwd | grep suryamani

Sample Output:
w

suryamani:x:1001:1001::/home/suryamani:/bin/bash
ev

●​ GID 1001 corresponds to the suryamani group.


3.​ Verify the group in /etc/group:
D

cat /etc/group | grep suryamani

Sample Output:

suryamani:x:1001:

4.​ Add suryamani to a secondary group DevSecOps:

sudo groupadd DevSecOps


sudo usermod -aG DevSecOps suryamani

cat /etc/group | grep DevSecOps

Sample Output:

DevSecOps:x:1002:suryamani

5.​ Check all groups for suryamani:

a
groups suryamani

ry
Sample Output:

suryamani : suryamani DevSecOps


su
1.2 Switch User (su)
ith
The su command switches to another user’s account.

Command:
w

su [username]
ev

Description:

●​ Switches to the specified user’s environment (prompts for their password).


●​ Use sudo su [username] if you have administrative privileges but don’t know the
D

user’s password.

Example:

1.​ Switch to suryamani:

su suryamani

Prompt:

Password:
2.​ Perform file operations as suryamani:

ls

touch file1.txt

ls -l

Sample Output:

a
-rw-r--r-- 1 suryamani suryamani 0 May 20 13:00 file1.txt

ry
●​ The file’s owner is suryamani, and the group is suryamani (primary group).
3.​ Exit back to the original user:

exit
su
ith
Note:

●​ Use sudo -i suryamani for a full login session with the user’s environment.
●​ Without sudo, su requires the target user’s password, which may cause “permission
denied” if not known.
w

2. SSH Key Generation (RSA)


ev

2.1 Generate RSA SSH Key

SSH keys are used for secure authentication between systems. In Ubuntu, RSA keys are
generated in the ~/.ssh directory.
D

Command:

cd ~/.ssh

ssh-keygen -t rsa -b 4096 -C "[email protected]"

Description:

●​ cd ~/.ssh: Navigates to the user’s .ssh directory (e.g., /home/ubuntu/.ssh).


●​ ssh-keygen: Generates a public-private key pair.
●​ -t rsa: Specifies RSA key type (widely compatible, used for legacy systems).
●​ -b 4096: Sets key length to 4096 bits for enhanced security (2048 is also common).
●​ -C: Adds a comment (e.g., email) for identification.

Example:

1.​ Navigate to .ssh:

cd ~/.ssh

ls

a
2.​ Generate an RSA key pair:

ry
ssh-keygen -t rsa -b 4096 -C "[email protected]"

Prompt:
su
Generating public/private rsa key pair.
ith
Enter file in which to save the key (/home/ubuntu/.ssh/id_rsa):

Enter passphrase (empty for no passphrase):

Enter same passphrase again:


w
ev

3.​ Press Enter for defaults (creates id_rsa private key and id_rsa.pub public key).
4.​ Verify:

ls
D

Sample Output:

id_rsa id_rsa.pub

Security Best Practices:

●​ Set permissions for SSH keys:

chmod 600 ~/.ssh/id_rsa


chmod 644 ~/.ssh/id_rsa.pub

●​ Use a passphrase for added security.


●​ Restrict .ssh directory access:

chmod 700 ~/.ssh

3. Jump Server Setup for Two EC2 Instances

a
3.1 What is a Jump Server?

ry
A jump server is an intermediary server used to securely access other servers in a private
network. In this scenario, you have two AWS EC2 instances:

●​ EC2-1 (Jump Server): Accessible from your local machine, with a public IP (e.g.,
su
203.0.113.1).
●​ EC2-2 (Private Server): In a private subnet, accessible only via EC2-1, with a private
IP (e.g., 10.0.0.2).
ith
You’ll generate an RSA key on EC2-1, transfer it to your local machine using SCP, then to
EC2-2, enabling secure communication via the jump server.

3.2 Prerequisites
w

●​ Two Ubuntu-based EC2 instances on AWS:


○​ EC2-1: Public IP (e.g., 203.0.113.1), accessible via SSH.
○​ EC2-2: Private IP (e.g., 10.0.0.2), accessible from EC2-1.
ev

●​ Security groups:
○​ EC2-1: Allow SSH (port 22) from your local machine’s IP.
○​ EC2-2: Allow SSH (port 22) from EC2-1’s private IP.
●​ SSH key for EC2-1 (e.g., ec2-key.pem) for initial access.
D

3.3 Workflow

This workflow generates an RSA key on EC2-1, transfers it to your local machine, then to
EC2-2, and sets up EC2-1 as a jump server to access EC2-2.

Step 1: Generate RSA Key on EC2-1

1.​ SSH into EC2-1 from your local machine:

ssh -i ec2-key.pem [email protected]


2.​ Generate an RSA key pair:

cd ~/.ssh

ssh-keygen -t rsa -b 4096 -C "jump-server-key"

●​ Press Enter for defaults (creates id_rsa and id_rsa.pub).


3.​ Set permissions:

chmod 600 ~/.ssh/id_rsa

chmod 644 ~/.ssh/id_rsa.pub

a
ry
Step 2: Transfer Public Key to Local Machine Using SCP

1.​ From your local machine, download the public key:


su
scp -i ec2-key.pem [email protected]:~/.ssh/id_rsa.pub ./jump-server-key.pub

●​ This saves jump-server-key.pub in your local directory.


ith
Step 3: Transfer Public Key to EC2-2

1.​ SSH into EC2-2 via EC2-1 (jump server):


w

○​ Add EC2-1’s key to your local SSH agent:

ssh-add ec2-key.pem
ev

●​ Connect to EC2-2 via EC2-1:

ssh -J [email protected] [email protected]


D

2.​ Add the public key to EC2-2’s authorized_keys:

mkdir -p ~/.ssh

cat >> ~/.ssh/authorized_keys < jump-server-key.pub

chmod 600 ~/.ssh/authorized_keys


●​ Alternatively, upload the key using SCP from your local machine:

scp -i ec2-key.pem jump-server-key.pub [email protected]:/tmp

Then, on EC2-1:

scp /tmp/jump-server-key.pub [email protected]:~/.ssh/authorized_keys

Step 4: Configure Jump Server Access

a
1.​ On EC2-1, ensure SSH access to EC2-2:

ssh-copy-id -i ~/.ssh/id_rsa [email protected]

ry
●​ This copies EC2-1’s public key to EC2-2’s authorized_keys.
su
Step 5: Test Jump Server Connection

1.​ From your local machine, connect to EC2-2 via EC2-1:


ith
ssh -J [email protected] [email protected]

2.​ Verify access:


w

whoami
ev

Sample Output:

ubuntu
D

Step 6: Secure File Transfer Using SCP via Jump Server

1.​ Transfer a file from EC2-1 to EC2-2:

scp /path/to/file [email protected]:/home/ubuntu/

2.​ Transfer a file from your local machine to EC2-2 via EC2-1:
scp -J [email protected] localfile.txt [email protected]:/home/ubuntu/

3.4 Security Best Practices

●​ Disable password authentication on both EC2 instances:


○​ Edit /etc/ssh/sshd_config:

sudo nano /etc/ssh/sshd_config

●​ Set:

a
PasswordAuthentication no

ry
●​ Restart SSH:
su
sudo systemctl restart sshd
ith
●​ Use 4096-bit RSA keys for better security.
●​ Regularly rotate SSH keys.
●​ Restrict security group rules to specific IPs.

3.5 Troubleshooting
w

●​ Permission Denied: Check key permissions (chmod 600) and authorized_keys.


●​ Connection Refused: Verify security group rules and SSH service:
ev

sudo systemctl status sshd


D

●​ Timeout: Ensure EC2 instances are running and network configurations are correct.

Practice Workflow
1.​ Create a user and verify groups:

sudo useradd -m suryamani

sudo passwd suryamani

sudo groupadd DevSecOps


sudo usermod -aG DevSecOps suryamani

cat /etc/passwd | grep suryamani

cat /etc/group | grep DevSecOps

2.​ Switch to suryamani and create a file:

su suryamani

touch file1.txt

a
ls -l

exit

ry
3.​ Set up RSA keys on EC2-1:
su
ssh -i ec2-key.pem [email protected]

cd ~/.ssh
ith
ssh-keygen -t rsa -b 4096 -C "jump-server-key"

4.​ Transfer keys and test jump server:


w

scp -i ec2-key.pem [email protected]:~/.ssh/id_rsa.pub ./jump-server-key.pub


ev

scp -i ec2-key.pem jump-server-key.pub [email protected]:/tmp

ssh -i ec2-key.pem [email protected]

scp /tmp/jump-server-key.pub [email protected]:~/.ssh/authorized_keys


D

ssh -J [email protected] [email protected]

Additional Notes
●​ Primary vs. Secondary Groups:
○​ Primary group owns the user’s files by default.
○​ Secondary groups provide additional access (e.g., shared directories).
●​ SSH Security:
○​ RSA keys with 4096-bit length are secure but slightly slower than ED25519.
○​ Restrict .ssh directory permissions to 700:

chmod 700 ~/.ssh

●​ Jump Server:
○​ Simplifies access to private EC2 instances in a VPC.
○​ Use ProxyJump in SSH config for easier access:

echo -e "Host ec2-2\n HostName 10.0.0.2\n ProxyJump [email protected]" >>


~/.ssh/config

a
●​ Man Pages: Use man [command] for details (e.g., man ssh-keygen, man scp).

ry
Ubuntu File Permissions
su
1. Understanding File Permissions
1.1 Permission String
ith
When you run ls -l in Ubuntu, the output shows permissions in a 10-character string, such
as drwxrwxr-x.
w

Breakdown:

●​ Position 1: Type of file


○​ d: Directory
ev

○​ -: Regular file
○​ l: Symbolic link
●​ Positions 2-4 (rwx): Permissions for the owner (user) who created the file.
●​ Positions 5-7 (rwx): Permissions for the group associated with the file.
D

●​ Positions 8-10 (r-x): Permissions for others (everyone else).

Permissions:

●​ r: Read (view or copy the file)


●​ w: Write (edit or delete the file)
●​ x: Execute (run the file as a program or access a directory)

Example:

ls -l
Sample Output:

drwxrwxr-x 2 ubuntu ubuntu 4096 May 20 13:00 mydir

-rw-r--r-- 1 ubuntu ubuntu 0 May 20 13:00 file.txt

●​ drwxrwxr-x:
○​ d: mydir is a directory.
○​ rwx (owner): The owner (ubuntu) can read, write, and execute.

a
○​ rwx (group): The group (ubuntu) can read, write, and execute.
○​ r-x (others): Others can read and execute, but not write.
●​ -rw-r--r--:

ry
○​ -: file.txt is a regular file.
○​ rw- (owner): The owner can read and write.
○​ r-- (group): The group can read.
su ○​ r-- (others): Others can read.

2. Numeric Representation of Permissions


ith
Permissions can be represented numerically, where each permission (r, w, x) has a value:

●​ r = 4 (read)
●​ w = 2 (write)
w

●​ x = 1 (execute)

2.1 Permission Table


ev

The table below maps permission combinations to numeric values:


D

Value r w x Permissio Symboli


n c

0 0 0 0 --- ---

1 0 0 1 --x --x
2 0 1 0 -w- -w-

3 0 1 1 -wx -wx

4 1 0 0 r-- r--

5 1 0 1 r-x r-x

a
6 1 1 0 rw- rw-

ry
7 1 1 1 rwx rwx
su
For drwxrwxr-x:
ith
●​ Owner: rwx = 7
●​ Group: rwx = 7
●​ Others: r-x = 5
w

●​ Numeric form: 775

3. Changing Permissions (chmod)


ev

The chmod command changes file or directory permissions in Ubuntu.

3.1 Numeric Mode


D

Use numeric values to set permissions for owner, group, and others.

Command:

chmod [numeric_value] [file_or_directory]

Example:

1.​ Create a file and check its permissions:


touch file.txt

ls -l file.txt

Sample Output:

-rw-r--r-- 1 ubuntu ubuntu 0 May 20 13:00 file.txt

●​ Default: rw-r--r-- (644)


2.​ Change permissions to rwxr-xr-x (755):

a
chmod 755 file.txt

ry
ls -l file.txt

su
Sample Output:

-rwxr-xr-x 1 ubuntu ubuntu 0 May 20 13:00 file.txt


ith
3.2 Symbolic Mode

Use symbolic notation to modify specific permissions.


w

Command:

chmod [who][operator][permission] [file_or_directory]


ev

●​ who: u (user/owner), g (group), o (others), a (all)


D

●​ operator: + (add), - (remove), = (set)


●​ permission: r, w, x

Example:

1.​ Add execute permission for the owner:

chmod u+x file.txt

ls -l file.txt
Sample Output:

-rwxr--r-- 1 ubuntu ubuntu 0 May 20 13:00 file.txt

2.​ Remove write permission for others:

chmod o-w file.txt

ls -l file.txt

a
Sample Output:

-rwxr--r-- 1 ubuntu ubuntu 0 May 20 13:00 file.txt

ry
su
4. Changing Groups (chgrp)
The chgrp command changes the group ownership of a file or directory.
ith
Command:

sudo chgrp [groupname] [file_or_directory]


w

Description:

●​ Changes the group associated with the file or directory.


ev

●​ Use -R for recursive changes (e.g., for directories and their contents).

Example:

1.​ Create a group and a file:


D

sudo groupadd DevSecOps

touch file.txt

ls -l file.txt

Sample Output:

-rw-r--r-- 1 ubuntu ubuntu 0 May 20 13:00 file.txt


●​ Group: ubuntu (default primary group of the user ubuntu).
2.​ Change the group to DevSecOps:

sudo chgrp DevSecOps file.txt

ls -l file.txt

Sample Output:

-rw-r--r-- 1 ubuntu DevSecOps 0 May 20 13:00 file.txt

a
ry
3.​ For a directory and its contents:

mkdir mydir
su
sudo chgrp -R DevSecOps mydir

ls -ld mydir
ith
Sample Output:

drwxr-xr-x 2 ubuntu DevSecOps 4096 May 20 13:00 mydir


w
ev

5. Changing Ownership (chown)


The chown command changes the owner (and optionally the group) of a file or directory.
D

Command:

sudo chown [username] [file_or_directory]

sudo chown [username]:[groupname] [file_or_directory]

Description:

●​ Changes the owner of the file or directory.


●​ Optionally changes the group as well.
●​ Use -R for recursive changes.
Example:

1.​ Create a user and a file:

sudo useradd -m suryamani

sudo passwd suryamani

touch file.txt

ls -l file.txt

a
Sample Output:

-rw-r--r-- 1 ubuntu ubuntu 0 May 20 13:00 file.txt

ry
2.​ Change the owner to suryamani:
su
sudo chown suryamani file.txt

ls -l file.txt
ith
Sample Output:

-rw-r--r-- 1 suryamani ubuntu 0 May 20 13:00 file.txt


w
ev

3.​ Change both owner and group:

sudo chown suryamani:DevSecOps file.txt

ls -l file.txt
D

Sample Output:

-rw-r--r-- 1 suryamani DevSecOps 0 May 20 13:00 file.txt

6. Special Permissions (Optional)


Ubuntu supports special permissions for advanced use cases:
●​ Setuid (4xxx): Runs a file as the owner (e.g., 4755).
●​ Setgid (2xxx): Runs a file as the group or inherits group for directories (e.g., 2755).
●​ Sticky Bit (1xxx): Prevents deletion of files in a directory by non-owners (e.g.,
1755).

Example:​
Set sticky bit on a directory:

chmod 1755 shared_dir

ls -ld shared_dir

a
Sample Output:

ry
drwxr-xr-t 2 ubuntu ubuntu 4096 May 20 13:00 shared_dir

su
●​ t indicates the sticky bit.

Practice Workflow
ith
1.​ Create a file and directory:

touch file.txt

mkdir mydir
w

ls -l
ev

2.​ Check and change permissions:

chmod 755 file.txt


D

ls -l file.txt

chmod u-w mydir

ls -ld mydir

3.​ Change group:

sudo groupadd DevSecOps


sudo chgrp DevSecOps file.txt

ls -l file.txt

4.​ Change owner:

sudo useradd -m suryamani

sudo chown suryamani file.txt

ls -l file.txt

a
5.​ Clean up:

ry
sudo userdel -r suryamani

sudo groupdel DevSecOps


su
rm file.txt

rmdir mydir
ith
Additional Notes
w

●​ Permission Denied: Use sudo for commands requiring administrative privileges


(e.g., chown, chgrp).
●​ Best Practices:
ev

○​ Follow the least privilege principle: Grant only necessary permissions.


○​ Avoid 777 (full permissions for all) unless absolutely required.
●​ Directory vs. File:
○​ x on a directory means you can access its contents.
D

○​ x on a file means it can be executed as a program.


●​ Man Pages: Use man [command] for details (e.g., man chmod, man chgrp).

Ubuntu Installation
1. Installing Nginx
1.1 Update Package Lists
Before installing any package, update the package lists to ensure you get the latest version.

Command:

sudo apt update

Description:

●​ Refreshes the package index to fetch the latest package versions.


●​ Requires sudo for administrative privileges.

Example:

a
sudo apt update

ry
Sample Output:
su
Hit:1 http://archive.ubuntu.com/ubuntu noble InRelease

Get:2 http://security.ubuntu.com/ubuntu noble-security InRelease [126 kB]

Fetched 126 kB in 1s (123 kB/s)


ith
Reading package lists... Done
w

1.2 Upgrade System Packages (Optional)

Upgrade installed packages to their latest versions for system stability.


ev

Command:

sudo apt upgrade -y


D

Description:

●​ -y: Automatically answers "yes" to prompts, making the process non-interactive.

1.3 Install Nginx

Install Nginx using the apt package manager.

Command:
sudo apt install nginx -y

Description:

●​ Installs Nginx and its dependencies.


●​ apt install is the modern command in Ubuntu (preferred over apt-get
install).
●​ -y: Skips confirmation prompts.

Example:

a
sudo apt install nginx -y

ry
Sample Output:

Reading package lists... Done


su
Building dependency tree... Done

The following NEW packages will be installed:


ith
nginx

0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.

After this operation, 2,345 kB of additional disk space will be used.


w

Setting up nginx (1.24.0-1ubuntu1) ...


ev

Note:

●​ After installation, Nginx starts automatically and listens on port 80.


D

●​ The default web page is located at


/var/www/html/index.nginx-debian.html.

1.4 Verify Installation

Check if Nginx is running and accessible.

Command:

curl http://localhost
Description:

●​ Fetches the default Nginx welcome page.


●​ If curl is not installed, install it:

sudo apt install curl -y

Sample Output:

<!DOCTYPE html>

<html>

a
<head>

ry
<title>Welcome to nginx!</title>

...

<body>
su
<h1>Welcome to nginx!</h1>

<p>If you see this page, the nginx web server is successfully installed and working.</p>
ith
...

</body>
w

</html>
ev

Alternative:

●​ Open a browser and visit http://<server-ip> (e.g., http://203.0.113.1 if


on an EC2 instance).
D

●​ Check the Nginx version:

nginx -v

Sample Output:

nginx version: nginx/1.24.0


2. Managing Nginx Services
2.1 Check Nginx Status

Use systemctl to check the status of the Nginx service.

Command:

systemctl status nginx

Description:

a
●​ Shows whether Nginx is active, running, or stopped.
●​ Displays recent logs and process details.

ry
Example:

systemctl status nginx


su
Sample Output:
ith
● nginx.service - A high performance web server and a reverse proxy server

Loaded: loaded (/lib/systemd/system/nginx.service; enabled; preset: enabled)

Active: active (running) since Tue 2025-05-20 13:00:00 UTC; 5min ago
w

Main PID: 1234 (nginx)


ev

Tasks: 2 (limit: 4651)

Memory: 5.2M

CPU: 45ms
D

CGroup: /system.slice/nginx.service

├─1234 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;

└─1235 nginx: worker process

2.2 Start Nginx

Start the Nginx service if it’s stopped.


Command:

sudo systemctl start nginx

Description:

●​ Starts the Nginx service.


●​ Requires sudo for administrative privileges.

Example:

sudo systemctl start nginx

a
systemctl status nginx

ry
2.3 Stop Nginx
su
Stop the Nginx service if needed.

Command:
ith
sudo systemctl stop nginx

Description:
w

●​ Stops the Nginx service, making the web server inaccessible.

Example:
ev

sudo systemctl stop nginx

systemctl status nginx


D

Sample Output:

● nginx.service - A high performance web server and a reverse proxy server

Loaded: loaded (/lib/systemd/system/nginx.service; enabled; preset: enabled)

Active: inactive (dead) since Tue 2025-05-20 13:05:00 UTC; 10s ago
2.4 Restart Nginx

Restart the Nginx service to apply configuration changes.

Command:

sudo systemctl restart nginx

Description:

●​ Stops and then starts the Nginx service.

a
2.5 Reload Nginx

ry
Reload Nginx to apply configuration changes without downtime.

Command:

su
sudo systemctl reload nginx

Description:
ith
●​ Reloads the configuration without interrupting active connections.

2.6 Enable Nginx on Boot


w

Ensure Nginx starts automatically on system boot.

Command:
ev

sudo systemctl enable nginx


D

Description:

●​ Enables the Nginx service to start on boot.

Example:

sudo systemctl enable nginx

Sample Output:
Synchronizing state of nginx.service with SysV service script with
/lib/systemd/systemd-sysv-install.

Executing: /lib/systemd/systemd-sysv-install enable nginx

2.7 Disable Nginx on Boot

Prevent Nginx from starting on boot.

Command:

sudo systemctl disable nginx

a
ry
Description:

●​ Disables automatic startup on boot.


su
Example:

sudo systemctl disable nginx


ith
3. Removing Nginx
w

3.1 Stop Nginx Service

Before removing Nginx, stop the service.


ev

Command:

sudo systemctl stop nginx


D

3.2 Remove Nginx

Uninstall Nginx while keeping configuration files.

Command:

sudo apt remove nginx -y

Description:
●​ Removes the Nginx package but retains configuration files (e.g., /etc/nginx).

Example:

sudo apt remove nginx -y

3.3 Purge Nginx (Optional)

Completely remove Nginx, including configuration files.

Command:

a
sudo apt purge nginx -y

ry
Description:

su
●​ Removes Nginx and its configuration files.

3.4 Clean Up Residual Files

Remove any leftover dependencies or files.


ith
Command:

sudo apt autoremove -y


w

sudo apt autoclean


ev

Description:

●​ autoremove: Removes unused dependencies.


●​ autoclean: Cleans up old package files.
D

4. Basic Nginx Usage


4.1 Configuration Files

Nginx configuration files are located in /etc/nginx:

●​ Main configuration: /etc/nginx/nginx.conf


●​ Site configurations: /etc/nginx/sites-available/ and
/etc/nginx/sites-enabled/
Example:​
View the main configuration:

cat /etc/nginx/nginx.conf

4.2 Default Web Page

The default Nginx web page is at /var/www/html/index.nginx-debian.html.

Example:​
Replace the default page:

a
echo "<h1>Hello, Ubuntu Nginx!</h1>" | sudo tee /var/www/html/index.html

ry
curl http://localhost

su
Sample Output:

<h1>Hello, Ubuntu Nginx!</h1>


ith
4.3 Logs

Nginx logs are stored in /var/log/nginx:


w

●​ Access log: /var/log/nginx/access.log


●​ Error log: /var/log/nginx/error.log
ev

Example:​
Check recent errors:

tail -n 10 /var/log/nginx/error.log
D

5. Troubleshooting
●​ Port 80 Conflict:
○​ If Nginx fails to start (e.g., "nginx: [emerg] bind() to 0.0.0.0:80 failed"):

sudo netstat -tuln | grep :80


●​ Stop the conflicting service (e.g., Apache):

sudo systemctl stop apache2

●​ Restart Nginx:

sudo systemctl start nginx

●​ Service Not Starting:


○​ Check status and logs:

a
systemctl status nginx

ry
journalctl -u nginx -n 50

su
●​ Permission Denied:
○​ Ensure you use sudo for commands requiring administrative access.

Practice Workflow
ith
1.​ Update and install Nginx:

sudo apt update


w

sudo apt install nginx -y


ev

2.​ Manage the Nginx service:

systemctl status nginx


D

sudo systemctl stop nginx

sudo systemctl start nginx

sudo systemctl enable nginx

3.​ Verify Nginx:

curl http://localhost

nginx -v
4.​ Remove Nginx:

sudo systemctl stop nginx

sudo apt purge nginx -y

sudo apt autoremove -y

Additional Notes

a
●​ Best Practices:
○​ Always run sudo apt update before installing packages.

ry
○​ Use systemctl reload instead of restart to avoid downtime when
updating configurations.
○​ Regularly check logs (/var/log/nginx) for errors.
su
●​ Configuration:
○​ Edit /etc/nginx/sites-available/default for custom site
configurations.
○​ Test configuration syntax:
ith
sudo nginx -t
w

●​ Man Pages: Use man [command] for details (e.g., man apt, man systemctl).

Ubuntu Grep, Awk, and Find


ev

1. Grep Command
D

1.1 Overview

grep searches for patterns (text or regular expressions) in files or input and outputs
matching lines.

Syntax:

grep [options] pattern [file...]


1.2 Common Options

●​ -i: Case-insensitive search.


●​ -r: Recursive search in directories.
●​ -n: Show line numbers.
●​ -v: Invert match (show non-matching lines).
●​ -l: Show only filenames with matches.

1.3 Examples

Example 1: Search for a String in a File

a
echo -e "Hello Ubuntu\nWelcome to Linux\nUbuntu is great" > file.txt

grep "Ubuntu" file.txt

ry
Sample Output:
su
Hello Ubuntu

Ubuntu is great
ith
Example 2: Case-Insensitive Search

grep -i "ubuntu" file.txt


w

Sample Output:
ev

Hello Ubuntu

Ubuntu is great
D

Example 3: Recursive Search in a Directory​


Search for "error" in all files under /var/log:

sudo grep -r "error" /var/log

Sample Output:

/var/log/syslog:May 20 13:00:00 ubuntu systemd[1]: error starting service


Example 4: Show Line Numbers

grep -n "Ubuntu" file.txt

Sample Output:

1:Hello Ubuntu

3:Ubuntu is great

a
ry
2. Awk Command
2.1 Overview
su
awk is a text-processing tool for extracting and manipulating data, especially useful for
columnar data.

Syntax:
ith
awk [options] 'pattern {action}' [file...]
w

2.2 Common Options and Features

●​ -F: Specify field separator (default is space).


ev

●​ $N: Access the Nth field (e.g., $1 for first field).


●​ NR: Line number.
●​ Patterns: Filter rows based on conditions.
D

2.3 Examples

Example 1: Print Specific Columns​


Create a sample file:

echo -e "name age city\nsuryamani 25 Delhi\nabhishek 30 Mumbai" > data.txt

awk '{print $1, $3}' data.txt

Sample Output:
name city

suryamani Delhi

abhishek Mumbai

Example 2: Use a Custom Field Separator​


For a comma-separated file:

echo -e "name,age,city\nsuryamani,25,Delhi" > data.csv

awk -F',' '{print $1 " lives in " $3}' data.csv

a
ry
Sample Output:

name lives in city


su
suryamani lives in Delhi

Example 3: Filter Rows​


ith
Print lines where age is greater than 25:

awk '$2 > 25 {print $1}' data.txt


w

Sample Output:
ev

abhishek

Example 4: Combine with grep​


D

Find lines with "Delhi" and extract the name:

grep "Delhi" data.txt | awk '{print $1}'

Sample Output:

suryamani
3. Find Command
3.1 Overview

find searches for files and directories in a specified path based on criteria like name, type,
or size.

Syntax:

find [path] [options]

a
3.2 Common Options

ry
●​ -type: Specify file type (f for file, d for directory).
●​ -name: Match filename (supports wildcards).
●​ -exec: Execute a command on found files.
●​ -mtime: Find files modified N days ago.
su
3.3 Examples

Example 1: Find Files by Name​


ith
Find all .txt files in /home/ubuntu:

find /home/ubuntu -type f -name "*.txt"


w

Sample Output:
ev

/home/ubuntu/file.txt

/home/ubuntu/data.txt
D

Example 2: Find Directories​


Find all directories named "test":

find /home -type d -name "test"

Sample Output:

/home/ubuntu/test
Example 3: Find and Delete Files​
Find and delete .log files older than 7 days:

find /var/log -type f -name "*.log" -mtime +7 -exec rm -v {} \;

Sample Output:

removed '/var/log/old.log'

Example 4: Combine with grep​

a
Find files containing "error":

ry
find /var/log -type f -exec grep -l "error" {} \;

su
Sample Output:

/var/log/syslog

/var/log/nginx/error.log
ith
Example 5: Use with xargs​
List all .txt files and count their lines:
w

find . -type f -name "*.txt" | xargs wc -l


ev

Sample Output:

3 ./file.txt
D

2 ./data.txt

5 total

4. Related Commands (Optional)


4.1 Sed Command

sed is a stream editor for text manipulation, often used with grep and awk.
Example: Replace "Ubuntu" with "Linux":

sed 's/Ubuntu/Linux/g' file.txt

Sample Output:

Hello Linux

Welcome to Linux

Linux is great

a
4.2 Combining Tools

ry
Search for "error" in log files, extract timestamps, and format:

su
grep "error" /var/log/syslog | awk '{print $1, $2, $3}' | sed 's/May/05/'

Sample Output:
ith
05 20 13:00:00
w

5. Troubleshooting
●​ Grep: No Such File or Directory:
ev

○​ Ensure the file exists:

ls file.txt
D

●​ Awk: Field Not Found:


○​ Check the field separator:

awk -F',' '{print $1}' data.csv

●​ Find: Permission Denied:


○​ Use sudo for restricted directories:

sudo find /root -name "*.txt"


Practice Workflow
1.​ Create sample files:

echo -e "Hello Ubuntu\nError in system\nUbuntu is great" > log.txt

echo -e "name,age,city\nsuryamani,25,Delhi" > data.csv

mkdir test

touch test/file1.txt

a
ry
2.​ Use grep to search:

grep "Error" log.txt


su
grep -i "Ubuntu" log.txt

3.​ Use awk to process data:


ith
awk -F',' '{print $1}' data.csv
w

4.​ Use find to locate files:

find . -type f -name "*.txt"


ev

find . -type d -name "test"


D

5.​ Combine commands:

grep "Ubuntu" log.txt | awk '{print $2}'

Ubuntu Shell Scripting


1. Shell Basics
1.1 What is a Shell?
A shell is a command-line interface for interacting with the operating system. In Ubuntu, the
default shell is Bash (Bourne Again Shell), located at /bin/bash.

Check Your Shell:

echo $SHELL

Sample Output:

/bin/bash

a
1.2 Writing a Shell Script

ry
A shell script is a file containing a series of commands. Use the #!/bin/bash shebang at
the top to specify the interpreter. We’ll use vim to edit scripts.
su
Example: Create a simple script:

vim hello.sh
ith
In vim:

1.​ Press i to enter insert mode.


w

2.​ Type:

#!/bin/bash
ev

echo "Hello, Ubuntu!"

3.​ Press Esc to exit insert mode.


D

4.​ Type :wq and press Enter to save and quit.

Make the Script Executable:

chmod +x hello.sh

Run the Script:

./hello.sh
Sample Output:

Hello, Ubuntu!

Vim Basics:

●​ i: Enter insert mode to edit.


●​ Esc: Return to normal mode.
●​ :w: Save the file.

a
●​ :q: Quit vim.
●​ :wq: Save and quit.
●​ :q!: Quit without saving (if you make a mistake).

ry
Best Practice:

su
●​ Always include the shebang (#!/bin/bash).
●​ Add comments for clarity (e.g., # This script prints a greeting).
●​ If stuck in vim, press Esc and type :q! to exit without saving.
ith
2. Variables and Arguments
2.1 Variables
w

Variables store data (strings, numbers) for use in scripts.

Syntax:
ev

variable_name=value

Example:​
D

Create a script using vim:

vim greet.sh

Add:

#!/bin/bash

name="Suryamani"
echo "Hello, $name!"

Save and exit (Esc, :wq).

Run:

chmod +x greet.sh

./greet.sh

a
Sample Output:

Hello, Suryamani!

ry
Types of Variables:
su
●​ Local Variables: Defined within the script (e.g., name="Suryamani").
●​ Environment Variables: Available system-wide (e.g., export
PATH="$PATH:/usr/local/bin").
ith
Quoting Rules:

●​ Use double quotes (") for strings with variables: echo "Hello, $name"
●​ Use single quotes (') to prevent variable expansion: echo 'Hello, $name'
w

2.2 Arguments
ev

Scripts can accept arguments passed at runtime.

Special Variables:

●​ $1, $2, ...: First, second, etc., arguments.


D

●​ $#: Number of arguments.


●​ $@: All arguments as a list.
●​ $?: Exit status of the last command (0 = success, non-zero = failure).

Example:

vim args.sh

Add:
#!/bin/bash

echo "First argument: $1"

echo "Second argument: $2"

echo "Total arguments: $#"

Save and exit (Esc, :wq).

Run:

a
chmod +x args.sh

./args.sh Ubuntu Linux

ry
Sample Output:
su
First argument: Ubuntu

Second argument: Linux


ith
Total arguments: 2
w

3. Control Structures
3.1 If, Else, and Elif
ev

The if statement executes code based on conditions.

Syntax:
D

if [ condition ]; then

# code

elif [ condition ]; then

# code

else

# code
fi

Example:

vim number.sh

Add:

#!/bin/bash

a
number=10

if [ $number -gt 5 ]; then

ry
echo "Number is greater than 5"

elif [ $number -eq 5 ]; then


su
echo "Number is equal to 5"

else
ith
echo "Number is less than 5"

fi
w

Save and exit (Esc, :wq).


ev

Run:

chmod +x number.sh

./number.sh
D

Sample Output:

Number is greater than 5

Common Conditions:

●​ -eq: Equal
●​ -ne: Not equal
●​ -gt: Greater than
●​ -lt: Less than
●​ -ge: Greater than or equal
●​ -le: Less than or equal

3.2 Loops

For Loop

Iterates over a list of items.

Syntax:

a
for item in list; do

# code

ry
done

su
Example:

vim loop.sh
ith
Add:

#!/bin/bash
w

for i in 1 2 3 4 5; do
ev

echo "Number: $i"

done
D

Save and exit (Esc, :wq).

Run:

chmod +x loop.sh

./loop.sh

Sample Output:
Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

While Loop

a
Runs as long as a condition is true.

Syntax:

ry
while [ condition ]; do

# code

done
su
ith
Example:

vim while.sh
w

Add:
ev

#!/bin/bash

count=1

while [ $count -le 5 ]; do


D

echo "Count: $count"

((count++))

done

Save and exit (Esc, :wq).

Run:
chmod +x while.sh

./while.sh

Sample Output:

Count: 1

Count: 2

Count: 3

a
Count: 4

Count: 5

ry
3.3 Case Statement
su
Alternative to if-elif for multiple conditions.

Syntax:
ith
case $variable in

pattern1)
w

# code

;;
ev

pattern2)

# code

;;
D

*)

# default case

;;

esac

Example:
vim case.sh

Add:

#!/bin/bash

fruit="apple"

case $fruit in

"apple")

a
echo "This is an apple"

;;

ry
"banana")

echo "This is a banana"


su
;;

*)
ith
echo "Unknown fruit"

;;

esac
w
ev

Save and exit (Esc, :wq).

Run:

chmod +x case.sh
D

./case.sh

Sample Output:

This is an apple

4. Functions
4.1 Defining Functions

Functions allow reusable code blocks.

Syntax:

function_name() {

# code

a
Example:

vim func.sh

ry
Add: su
#!/bin/bash

greet() {
ith
echo "Hello, $1!"

greet "Suryamani"
w

greet "Abhishek"
ev

Save and exit (Esc, :wq).

Run:
D

chmod +x func.sh

./func.sh

Sample Output:

Hello, Suryamani!

Hello, Abhishek!
4.2 Return Values

Use return to send a status code (0-255).

Example:

vim check.sh

Add:

a
#!/bin/bash

ry
check_number() {

if [ $1 -gt 0 ]; then

su
else
return 0

return 1
ith
fi

}
w

check_number 5

echo "Exit status: $?"


ev

Save and exit (Esc, :wq).

Run:
D

chmod +x check.sh

./check.sh

Sample Output:

Exit status: 0
5. Server Backup Script
5.1 Backup Script Example

This script backs up a directory, compresses it, and logs the process.

Script:

vim backup.sh

Add:

a
#!/bin/bash

ry
# Variables
su
SOURCE_DIR="/var/log"

BACKUP_DIR="/home/ubuntu/backups"

DATE=$(date +%Y%m%d_%H%M%S)
ith
BACKUP_FILE="$BACKUP_DIR/backup_$DATE.tar.gz"

LOG_FILE="/home/ubuntu/backup.log"
w

# Create backup directory if it doesn't exist


ev

if [ ! -d "$BACKUP_DIR" ]; then

mkdir -p "$BACKUP_DIR"
D

echo "$(date): Created backup directory $BACKUP_DIR" >> "$LOG_FILE"

fi

# Perform backup

echo "$(date): Starting backup of $SOURCE_DIR" >> "$LOG_FILE"

if tar -czf "$BACKUP_FILE" "$SOURCE_DIR" 2>> "$LOG_FILE"; then

echo "$(date): Backup completed: $BACKUP_FILE" >> "$LOG_FILE"


else

echo "$(date): Backup failed!" >> "$LOG_FILE"

exit 1

fi

# Delete backups older than 7 days

find "$BACKUP_DIR" -type f -name "*.tar.gz" -mtime +7 -delete

a
echo "$(date): Deleted backups older than 7 days" >> "$LOG_FILE"

ry
Save and exit (Esc, :wq).

Explanation:
su
●​ Variables: Define source, backup directory, and log file.
●​ Error Handling: Check if backup directory exists; log errors if tar fails.
●​ Compression: Use tar -czf to create a compressed .tar.gz file.
ith
●​ Cleanup: Delete backups older than 7 days using find.

Run the Script:

chmod +x backup.sh
w

./backup.sh
ev

Check Logs:

cat /home/ubuntu/backup.log
D

Sample Output:

Tue May 20 14:00:00 IST 2025: Starting backup of /var/log

Tue May 20 14:00:01 IST 2025: Backup completed:


/home/ubuntu/backups/backup_20250520_140001.tar.gz

Tue May 20 14:00:01 IST 2025: Deleted backups older than 7 days
6. Scheduled Backup (Cron Job)
6.1 Setting Up a Cron Job

Cron is a job scheduler in Ubuntu for automating tasks.

Syntax (in crontab):

* * * * * /path/to/script.sh

# minute (0-59), hour (0-23), day of month (1-31), month (1-12), day of week (0-6)

a
Example: Schedule the backup script to run daily at 2 AM.

ry
1.​ Edit the crontab file:

crontab -e
su
●​ If prompted, select vim as the editor.
2.​ Add the following line:
ith
0 2 * * * /home/ubuntu/backup.sh

●​ 0 2 * * *: Runs at 2:00 AM daily.


w

3.​ Save and exit (Esc, :wq).

Verify Cron Job:


ev

crontab -l
D

Sample Output:

0 2 * * * /home/ubuntu/backup.sh

Common Schedules:

●​ Daily at midnight: 0 0 * * *
●​ Weekly on Sunday at 3 AM: 0 3 * * 0
●​ Hourly: 0 * * * *
7. Daily Tasks of a Linux Admin
7.1 Monitoring System Resources

Check CPU, memory, and disk usage:

top

df -h

free -h

a
●​ top: Real-time system monitoring.
●​ df -h: Disk usage in human-readable format.

ry
●​ free -h: Memory usage.

7.2 Log Management


su
Check and rotate logs to manage disk space:

tail -n 50 /var/log/syslog
ith
sudo logrotate -f /etc/logrotate.conf

7.3 User Management


w

Monitor user activity and manage accounts:


ev

who

last

sudo useradd -m newuser


D

sudo passwd newuser

7.4 Security Checks

Check for open ports and failed login attempts:

sudo netstat -tuln

grep "Failed" /var/log/auth.log


7.5 Backup Verification

Verify that backups are running:

cat /home/ubuntu/backup.log

ls -lh /home/ubuntu/backups

7.6 Package Updates

a
Keep the system updated:

ry
sudo apt update

sudo apt upgrade -y

su
8. Debugging and Error Handling
ith
8.1 Debugging Scripts

Use set -x to debug scripts by printing commands as they execute.

#!/bin/bash
w

set -x
ev

echo "Debugging example"

number=5

echo "Number is $number"


D

Sample Output:

+ echo Debugging example

Debugging example

+ number=5

+ echo Number is 5
Number is 5

8.2 Error Handling

Check for errors and exit on failure:

#!/bin/bash

if ! command; then

echo "Command failed"

a
exit 1

fi

ry
su
9. Troubleshooting
●​ Permission Denied:
○​ Ensure the script is executable:
ith
chmod +x script.sh
w

●​ Cron Job Not Running:


○​ Check cron logs:

grep CRON /var/log/syslog


ev

●​ Ensure the script has a shebang (#!/bin/bash).


D

●​ Vim Issues:
○​ If stuck, press Esc and type :q! to exit without saving.
○​ Install vim if not present:

sudo apt install vim -y

Practice Workflow
1.​ Create a script with vim:
vim myscript.sh

Add:

#!/bin/bash

name=$1

for i in 1 2 3; do

echo "Hello, $name! Count: $i"

a
done

ry
Save and exit (Esc, :wq).

2.​ Run the script:


su
chmod +x myscript.sh

./myscript.sh Suryamani
ith
Sample Output:

Hello, Suryamani! Count: 1


w

Hello, Suryamani! Count: 2


ev

Hello, Suryamani! Count: 3

3.​ Schedule the backup script:


D

vim backup.sh

# Add the backup script from Section 5

crontab -e

# Add: 0 2 * * * /home/ubuntu/backup.sh

4.​ Perform daily admin tasks:


top

df -h

tail -n 50 /var/log/syslog

Linux Interview Questions: Beginner and


Mid-Level
1. Beginner-Level Interview Questions

a
Q1: What is Linux, and why is it used?

ry
Answer: Linux is an open-source operating system kernel used in distributions like Ubuntu.
It’s used for its stability, security, and flexibility in servers, desktops, and embedded systems.
For example, Ubuntu is widely used for web servers due to its reliability.
su
Follow-Up: Name a few Linux distributions (e.g., Ubuntu, CentOS, Fedora).
ith
Q2: What is the difference between bash and sh?

Answer: bash (Bourne Again Shell) is an enhanced version of sh (Bourne Shell). Bash
includes additional features like command history and tab completion. In Ubuntu,
w

/bin/bash is the default shell, while /bin/sh is often a symbolic link to bash or another
shell like dash.
ev

Example:

echo $SHELL
D

Output:

/bin/bash

Q3: How do you check the current directory in Linux?

Answer: Use the pwd command to print the current working directory.
Example:

pwd

Output:

/home/ubuntu

a
Q4: What does the ls command do, and what are some common
options?

ry
Answer: The ls command lists files and directories. Common options include:

●​ -l: Long format (shows permissions, owner, etc.).


su
●​ -a: Show hidden files (starting with .).
●​ -h: Human-readable file sizes (e.g., KB, MB).

Example:
ith
ls -la
w

Output:

drwxr-xr-x 3 ubuntu ubuntu 4096 May 20 14:00 .


ev

drwxr-xr-x 5 root root 4096 May 20 14:00 ..

-rw-r--r-- 1 ubuntu ubuntu 0 May 20 14:00 file.txt


D

Q5: How do you create a directory in Linux?

Answer: Use the mkdir command to create a directory.

Example:

mkdir mydir

ls
Output:

mydir

Q6: How do you create an empty file in Linux?

Answer: Use the touch command to create an empty file.

a
Example:

ry
touch file.txt

ls

Output:
su
file.txt
ith
w

Q7: What does the cat command do?

Answer: The cat command displays the contents of a file.


ev

Example:

echo "Hello, Ubuntu!" > file.txt


D

cat file.txt

Output:

Hello, Ubuntu!

Q8: How do you check the disk usage of a directory?


Answer: Use the du command to check disk usage, often with -h for human-readable
format. Use df -h to check overall disk usage.

Example:

du -h /home/ubuntu

Output:

4.0K /home/ubuntu

a
ry
Q9: What are file permissions in Linux, and how do you read them?

Answer: File permissions control access to files and directories, shown in a 10-character
su
string (e.g., -rwxr-xr-x):

●​ Position 1: Type (- for file, d for directory).


●​ Positions 2-4: Owner permissions (rwx = read, write, execute).
ith
●​ Positions 5-7: Group permissions.
●​ Positions 8-10: Others’ permissions.

Example:
w

ls -l file.txt
ev

Output:

-rw-r--r-- 1 ubuntu ubuntu 0 May 20 14:00 file.txt


D

●​ Owner (ubuntu) has read/write (rw-), group and others have read (r--).

Q10: How do you change file permissions in Linux?

Answer: Use the chmod command. Permissions can be set numerically (e.g., 755) or
symbolically (e.g., u+x).

Example:
chmod 755 file.txt

ls -l file.txt

Output:

-rwxr-xr-x 1 ubuntu ubuntu 0 May 20 14:00 file.txt

a
Q11: How do you change the owner of a file?

Answer: Use the chown command.

ry
Example:

su
sudo chown suryamani file.txt

ls -l file.txt
ith
Output:

-rw-r--r-- 1 suryamani ubuntu 0 May 20 14:00 file.txt


w
ev

Q12: What does the grep command do?

Answer: grep searches for a pattern in files or input and outputs matching lines.
D

Example:

echo -e "Hello\nUbuntu\nLinux" > file.txt

grep "Ubuntu" file.txt

Output:

Ubuntu
Q13: How do you check running processes in Linux?

Answer: Use the ps command to list processes or top for real-time monitoring.

Example:

ps aux | head -2

Output:

a
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

ry
root 1 0.0 0.1 168432 8928 ? Ss 14:00 0:01 /sbin/init

su
Q14: How do you kill a process in Linux?

Answer: Use the kill command with the process ID (PID).


ith
Example:

ps aux | grep sleep


w

# Assume PID is 1234

kill 1234
ev
D

Q15: What is the purpose of the /etc/passwd file?

Answer: The /etc/passwd file stores user account information, including username, UID,
GID, home directory, and shell.

Example:

head -1 /etc/passwd

Output:
root:x:0:0:root:/root:/bin/bash

Q16: How do you install a package in Ubuntu?

Answer: Use apt to install packages.

Example:

sudo apt update

a
sudo apt install vim -y

ry
su
Q17: What does the man command do?

Answer: The man command displays the manual page for a command, providing usage and
options.
ith
Example:

man ls
w
ev

Q18: How do you redirect output to a file in Linux?

Answer: Use > to overwrite or >> to append output to a file.

Example:
D

echo "Test" > output.txt

cat output.txt

Output:

Test
Q19: What is a symbolic link, and how do you create one?

Answer: A symbolic link (symlink) is a shortcut to another file or directory. Use ln -s to


create one.

Example:

ln -s file.txt link.txt

ls -l link.txt

a
Output:

ry
lrwxrwxrwx 1 ubuntu ubuntu 8 May 20 14:00 link.txt -> file.txt

su
Q20: How do you check the system’s uptime?
ith
Answer: Use the uptime command to see how long the system has been running.

Example:

uptime
w
ev

Output:

14:00:00 up 1 day, 2:00, 2 users, load average: 0.01, 0.02, 0.03


D

2. Mid-Level Interview Questions


Q21: What is the difference between a hard link and a symbolic link?

Answer:

●​ Hard Link: Points directly to the inode of a file; deleting the original file doesn’t affect
the link (ln file hardlink).
●​ Symbolic Link: A pointer to the file path; deleting the original file breaks the link (ln
-s file symlink).
Example:

ln file.txt hardlink.txt

ln -s file.txt symlink.txt

ls -l

Output:

-rw-r--r-- 2 ubuntu ubuntu 0 May 20 14:00 file.txt

a
-rw-r--r-- 2 ubuntu ubuntu 0 May 20 14:00 hardlink.txt

lrwxrwxrwx 1 ubuntu ubuntu 8 May 20 14:00 symlink.txt -> file.txt

ry
su
Q22: How do you find files modified in the last 7 days?

Answer: Use the find command with -mtime.


ith
Example:

find /home -type f -mtime -7


w

●​ -mtime -7: Files modified within the last 7 days.


ev

Q23: What does the awk command do, and how do you use it to extract a
column?
D

Answer: awk processes text and extracts data, often used for columnar data. Use $N to
access the Nth field.

Example:

echo -e "name age\nsuryamani 25" > data.txt

awk '{print $2}' data.txt


Output:

age

25

Q24: How do you schedule a task in Linux using cron?

Answer: Use crontab to schedule tasks. Edit with crontab -e and add a line in the
format: minute hour day month day-of-week command.

a
Example: Run a script daily at 2 AM:

ry
crontab -e

Add:
su
0 2 * * * /home/ubuntu/backup.sh
ith

Q25: What is the purpose of the /etc/fstab file?


w

Answer: The /etc/fstab file defines how disk partitions, filesystems, and mount points
are mounted at boot.
ev

Example:

cat /etc/fstab
D

Sample Output:

/dev/sda1 / ext4 defaults 0 1

Q26: How do you monitor system logs in real-time?


Answer: Use tail -f to monitor logs in real-time.

Example:

tail -f /var/log/syslog

Output:

May 20 14:00:01 ubuntu CRON[1234]: (root) CMD (command)

a
Q27: What is a shell script, and how do you write a simple one?

ry
Answer: A shell script is a file with commands executed by the shell. Use #!/bin/bash at
the top.
su
Example:

vim script.sh
ith
Add:

#!/bin/bash
w

echo "Hello, $1!"


ev

Run:

chmod +x script.sh
D

./script.sh Ubuntu

Output:

Hello, Ubuntu!
Q28: How do you check network connectivity in Linux?

Answer: Use ping to test connectivity or netstat to check open ports.

Example:

ping -c 4 google.com

Output:

4 packets transmitted, 4 received, 0% packet loss

a
ry
Q29: What does the top command do, and how is it different from htop?

Answer:su
●​ top: Displays real-time system processes (CPU, memory usage).
●​ htop: An enhanced version of top with a user-friendly interface and additional
ith
features like scrolling and process killing.

Example:

top
w
ev

Q30: How do you find and kill a process using a specific port?

Answer: Use netstat or ss to find the PID, then kill it.


D

Example:

sudo netstat -tuln | grep :80

# Assume PID is 1234

sudo kill 1234


Q31: What is the purpose of the export command in a shell script?

Answer: export makes a variable available to child processes (environment variable).

Example:

export MY_VAR="test"

bash -c 'echo $MY_VAR'

Output:

a
test

ry
su
Q32: How do you redirect both stdout and stderr to a file?

Answer: Use > for stdout and 2> for stderr, or combine with &>.

Example:
ith
ls nonexistent 2> error.log

cat error.log
w

Output:
ev

ls: cannot access 'nonexistent': No such file or directory


D

Q33: What is the difference between sudo and su?

Answer:

●​ sudo: Runs a single command as another user (usually root) with your password.
●​ su: Switches to another user (e.g., root) and requires the target user’s password.

Example:

sudo ls /root
su root

Q34: How do you set up a basic backup script in Linux?

Answer: Use tar to create a backup and add error handling.

Example:

#!/bin/bash

a
tar -czf /backup/backup_$(date +%Y%m%d).tar.gz /var/log

ry
if [ $? -eq 0 ]; then

echo "Backup successful"

else su
echo "Backup failed"

fi
ith
w

Q35: What is the purpose of the /var/log directory?

Answer: The /var/log directory stores system logs, like /var/log/syslog (general
ev

logs) and /var/log/auth.log (authentication logs).

Example:

ls /var/log
D

Output:

syslog auth.log dpkg.log

Q36: How do you check the kernel version in Linux?


Answer: Use uname -r to check the kernel version.

Example:

uname -r

Output:

5.15.0-73-generic

a
Q37: What is logrotate, and why is it used?

ry
Answer: logrotate is a utility to rotate, compress, and manage log files to prevent them
from growing too large.
su
Example:

sudo logrotate -f /etc/logrotate.conf


ith

Q38: How do you find the largest files in a directory?


w

Answer: Use du with sort to find the largest files.


ev

Example:

du -h /home | sort -hr | head -5


D

Output:

1.2G /home/ubuntu

500M /home/ubuntu/largefile

Q39: What is the purpose of the ~/.bashrc file?


Answer: The ~/.bashrc file contains Bash shell configurations (e.g., aliases, environment
variables) for a user.

Example:

echo "alias ll='ls -la'" >> ~/.bashrc

source ~/.bashrc

Q40: How do you troubleshoot a service that fails to start?

a
Answer: Check the service status and logs:

ry
1.​ Use systemctl status to see the status.
2.​ Check logs with journalctl.
su
Example:

systemctl status nginx

journalctl -u nginx -n 50
ith
Quiz Questions
w

Question 1: Linux Commands


ev

Which command displays the current working directory?​


A) ls​
B) cd​
C) pwd​
D

D) dir

Answer: C​
Explanation: The pwd command prints the current working directory's full path.

Question 2: User Management


Which command creates a new user with a home directory?​
A) useradd -m john​
B) adduser john​
C) usermod john​
D) deluser john

Answer: A​
Explanation: useradd -m creates a user with a home directory. adduser is also valid but
is more interactive.

Question 3: Groups

a
How do you add a user to an existing group?​
A) groupadd user group​

ry
B) usermod -aG group user​
C) useradd -g group user​
D) gpasswd user group
su
Answer: B​
Explanation: usermod -aG group user appends the user to the specified group without
removing them from other groups.
ith
Question 4: SSH
w

What command connects to an AWS EC2 instance using a private key?​


A) ssh -i key.pem ec2-user@ec2-host​
B) scp key.pem ec2-user@ec2-host​
ev

C) ssh ec2-user@ec2-host​
D) ssh -key key.pem ec2-user@ec2-host

Answer: A​
Explanation: ssh -i key.pem specifies the private key for secure connection to an EC2
D

instance.

Question 5: SCP
Which command copies a local directory to an AWS EC2 instance?​
A) scp -i key.pem -r /local/dir ec2-user@ec2-host:/remote/dir​
B) scp -i key.pem /local/dir ec2-user@ec2-host:/remote/dir​
C) ssh -i key.pem /local/dir ec2-user@ec2-host:/remote/dir​
D) scp -r /local/dir ec2-user@ec2-host:/remote/dir

Answer: A​
Explanation: scp -i key.pem -r recursively copies a directory to the EC2 instance
using the private key.

Question 6: Grep
What does grep "error" /var/log/syslog do?​

a
A) Lists all files containing "error".​
B) Searches for lines containing "error" in /var/log/syslog.​

ry
C) Deletes lines with "error" in /var/log/syslog.​
D) Counts all files in /var/log.

Answer: B​
su
Explanation: grep searches for the specified pattern ("error") in the given file and outputs
matching lines.
ith
Question 7: Awk
What does awk '{print $1}' file.txt do?​
w

A) Prints the entire file.​


B) Prints the first column of each line in file.txt.​
C) Prints the last column of each line in file.txt.​
ev

D) Counts the number of lines in file.txt.

Answer: B​
Explanation: awk '{print $1}' extracts and prints the first field (column) of each line,
using whitespace as the delimiter.
D

Question 8: Find
What does find / -type f -name "*.log" do?​
A) Finds all directories named "*.log".​
B) Finds all files with the .log extension.​
C) Deletes all .log files.​
D) Lists all files in the current directory.
Answer: B​
Explanation: find / -type f -name "*.log" searches for files (-type f) with
names matching *.log across the filesystem.

Question 9: File Permissions


What does chmod 644 file.txt set?​
A) Read/write for owner, read for group and others.​
B) Read/write for all users.​
C) Execute for owner, read for group and others.​

a
D) No permissions for anyone.

Answer: A​

ry
Explanation: 644 sets read/write (6) for the owner and read-only (4) for group and others.

su
Question 10: Installation
Which command installs a package on a Debian-based system?​
ith
A) yum install package​
B) apt-get install package​
C) rpm -i package​
D) dnf install package
w

Answer: B​
Explanation: apt-get install is used to install packages on Debian-based systems like
Ubuntu.
ev

Question 11: Systemctl


D

What does systemctl restart nginx do?​


A) Stops the nginx service.​
B) Starts the nginx service.​
C) Stops and then starts the nginx service.​
D) Checks the status of the nginx service.

Answer: C​
Explanation: systemctl restart stops and immediately starts the specified service.
Question 12: Shell Scripting
What is the shebang line in a Bash script?​
A) #!/bin/bash​
B) # This is a comment​
C) echo "Hello"​
D) exit 0

Answer: A​
Explanation: The shebang (#!/bin/bash) specifies the interpreter for the script, in this
case, Bash.

a
ry
Question 13: Variables
How do you assign a variable in a Bash script?​
A) VAR="value"​
su
B) VAR=value()​
C) set VAR=value​
D) VAR:=value
ith
Answer: A​
Explanation: In Bash, variables are assigned using VAR="value" without spaces around
the equals sign.
w

Question 14: Arguments


ev

How do you access the first argument passed to a Bash script?​


A) $0​
B) $1​
D

C) $@​
D) $#

Answer: B​
Explanation: $1 refers to the first command-line argument passed to the script.

Question 15: If-Else


What does if [ "$VAR" -eq 10 ]; then check?​
A) If $VAR is greater than 10.​
B) If $VAR is equal to 10.​
C) If $VAR is less than 10.​
D) If $VAR is a string.

Answer: B​
Explanation: The -eq operator checks if the variable equals the specified number.

Question 16: Loops

a
What does for i in {1..5}; do do in a Bash script?​

ry
A) Loops 5 times, setting i from 1 to 5.​
B) Loops indefinitely.​
C) Loops over files in the current directory.​
D) Loops over command-line arguments.
su
Answer: A​
Explanation: The for loop iterates over the range {1..5}, setting i to 1, 2, 3, 4, and 5.
ith
Question 17: Functions
w

How do you define a function in a Bash script?​


A) function my_func() { ... }​
B) my_func = () { ... }​
ev

C) def my_func(): { ... }​


D) my_func() => { ... }

Answer: A​
Explanation: Functions in Bash are defined using function name() { ... } or simply
D

name() { ... }.

Question 18: Server Backup


What is the purpose of the scp command in the AWS backup script?​
A) To start a service on the EC2 instance.​
B) To copy files securely to/from an EC2 instance.​
C) To monitor disk usage on the EC2 instance.​
D) To delete files on the EC2 instance.

Answer: B​
Explanation: scp securely copies files between local and remote systems, such as an EC2
instance.

Question 19: Cronjob


What does the cron entry * * * * * script.sh do?​

a
A) Runs script.sh every minute.​
B) Runs script.sh every hour.​
C) Runs script.sh every day.​

ry
D) Runs script.sh once at system startup.

Answer: A​
su
Explanation: * * * * * specifies every minute of every hour, day, month, and weekday.
ith
Question 20: File Permissions (AWS)
Why is chmod 400 key.pem used in the AWS SCP setup?​
A) To make the key file executable.​
B) To set read-only permissions for the owner.​
w

C) To allow all users to read the key file.​


D) To delete the key file.
ev

Answer: B​
Explanation: chmod 400 sets the key file to read-only for the owner, ensuring security for
SSH/SCP operations.
D

You might also like