1. Which command lists all files including hidden ones in Linux?
Difficulty: EasyType: MCQTopic: Linux Commands
The command ls -a shows all files, including hidden ones that start with a dot.
It is commonly used to inspect configuration files like .bashrc or .gitignore.
Correct Answer: ls -a
2. Which command prints the current working directory path?
Difficulty: EasyType: MCQTopic: Path Navigation
The pwd command stands for 'print working directory'. It displays the full absolute path of your current location in the file system.
It is useful for verifying where your script or command is being executed.
Correct Answer: pwd
3. Which command moves you one directory up in Linux?
Difficulty: EasyType: MCQTopic: Path Navigation
The command cd .. navigates to the parent directory of the current one.
Two dots always refer to the directory above the current path.
Correct Answer: cd ..
4. Which command combination creates and removes directories?
Difficulty: EasyType: MCQTopic: Linux Commands
- mkdir and rmdir
- make and delete
- create and rm
- touch and del
mkdir creates a new directory, while rmdir removes an empty one.
For non-empty directories, you can use rm -r to delete them recursively.
Correct Answer: mkdir and rmdir
Example Code
mkdir newfolder
rmdir newfolder
5. Which command moves files in Linux?
Difficulty: MediumType: MCQTopic: File Operations
mv is used to move files or rename them. When used between different directories, it transfers the file.
If used within the same directory with a new name, it simply renames the file.
Correct Answer: mv
Example Code
mv file.txt /home/user/docs/
6. Which command displays file content one screen at a time?
Difficulty: MediumType: MCQTopic: File Viewing
The less command displays large text files one page at a time and allows scrolling up or down.
It is more memory-efficient than cat for reading log or config files.
Correct Answer: less
Example Code
less /var/log/syslog
7. Which option with rm is required to delete directories recursively?
Difficulty: MediumType: MCQTopic: File Operations
The -r (recursive) flag allows rm to delete directories and their contents.
To bypass confirmation prompts, -rf is commonly used but should be applied carefully.
Correct Answer: -r
Example Code
rm -r myfolder
8. Which command finds files by name in the current directory and subdirectories?
Difficulty: MediumType: MCQTopic: File Finding
The find command searches for files or directories based on patterns or attributes.
It is highly flexible, allowing searches by name, size, or modification time.
Correct Answer: find
Example Code
find . -name 'config.json'
9. What does the grep command do?
Difficulty: MediumType: MCQTopic: Grep Regex
- Deletes files
- Searches text within files
- Renames directories
- Finds users
grep stands for 'global regular expression print'. It searches for specific patterns of text within one or more files.
It is often used in pipelines to filter command output.
Correct Answer: Searches text within files
Example Code
grep 'error' app.log
10. Explain the Linux directory structure and its top-level folders.
Difficulty: EasyType: SubjectiveTopic: Filesystem Basics
Linux follows a hierarchical file structure starting with the root directory (/).
Key directories include /bin for essential commands, /etc for configuration files, /home for user data, and /var for logs and variable files.
11. What is the difference between absolute and relative paths?
Difficulty: MediumType: SubjectiveTopic: Path Navigation
An absolute path specifies the full location starting from the root directory (/). It’s independent of the current directory.
A relative path is defined in relation to the current directory and doesn’t start with a slash. It’s shorter but depends on context.
12. Differentiate between piping (|) and redirection (>).
Difficulty: MediumType: SubjectiveTopic: Pipes Redirects
Piping sends the output of one command directly as input to another, allowing command chaining like grep or sort.
Redirection, on the other hand, writes output to a file or reads input from a file. It’s used for saving logs or output results.
13. What are wildcards in Linux and how are they used?
Difficulty: MediumType: SubjectiveTopic: Wildcards Globbing
Wildcards are special characters used to match file names or patterns. The most common are * for multiple characters and ? for a single character.
They are useful in commands like ls, rm, or cp for handling groups of files efficiently.
14. How do you view command history and create command aliases?
Difficulty: MediumType: SubjectiveTopic: Linux Commands
You can view your previous commands with the history command. Each command is numbered and can be re-run using !number.
Aliases let you create shortcuts for long commands using the alias keyword, improving productivity during repeated tasks.
Example Code
alias ll='ls -alF'
unalias ll
15. Which command changes file permissions in Linux?
Difficulty: EasyType: MCQTopic: File Permissions
chmod stands for 'change mode' and is used to modify read, write, and execute permissions of files or directories.
You can specify permissions using symbolic notation (rwx) or numeric codes (like 755 or 644).
Correct Answer: chmod
Example Code
chmod 755 script.sh
16. Which command changes the ownership of a file in Linux?
Difficulty: MediumType: MCQTopic: File Ownership
chown means 'change owner'. It allows an administrator to change the file owner and optionally its group.
Only the root user or the file’s current owner can modify ownership permissions.
Correct Answer: chown
Example Code
sudo chown ubuntu:devops app.log
17. In the permission string -rwxr-xr--, what does the second group (r-x) represent?
Difficulty: MediumType: MCQTopic: File Permissions
- Owner permissions
- Group permissions
- Other permissions
- Root access
Linux permission strings are divided into three sets — owner, group, and others.
The second triplet (r-x) shows what permissions the file’s group has. Here, they can read and execute but not write.
Correct Answer: Group permissions
18. Which command creates a new user account?
Difficulty: MediumType: MCQTopic: User Management
- adduser
- useradd
- newuser
- createuser
useradd creates a new user account on the system. It can also specify home directories, groups, and shells.
The adduser command is a user-friendly wrapper available in some Linux distributions.
Correct Answer: useradd
Example Code
sudo useradd -m -s /bin/bash devuser
19. Which command is used to change a user's password?
Difficulty: EasyType: MCQTopic: Password Management
- chpass
- passwd
- userpwd
- resetpwd
passwd allows users or administrators to update account passwords securely.
When executed, it prompts for the current password and then for the new one twice for confirmation.
Correct Answer: passwd
20. Which command displays currently running processes?
Difficulty: MediumType: MCQTopic: Process Monitoring
The ps command (process status) lists active processes along with their IDs, owners, and CPU usage.
The -ef option shows all processes in full format, often used with grep to locate specific tasks.
Correct Answer: ps
Example Code
ps -ef | grep nginx
21. Which signal is sent by default when you run the kill command without specifying one?
Difficulty: MediumType: MCQTopic: Process Signals
- SIGSTOP
- SIGTERM
- SIGKILL
- SIGHUP
By default, kill sends the SIGTERM signal, requesting the process to terminate gracefully.
To forcefully stop a process, SIGKILL (-9) can be used, but it doesn’t allow cleanup operations.
Correct Answer: SIGTERM
22. What does the top command display?
Difficulty: MediumType: MCQTopic: Process Monitoring
- Only disk usage
- System summary and live process information
- File structure details
- Kernel logs
top provides real-time system information including CPU, memory, and running processes.
It helps administrators monitor system performance and identify resource-heavy applications.
Correct Answer: System summary and live process information
23. Which command adjusts the scheduling priority of a process?
Difficulty: HardType: MCQTopic: Process Priority
- renice
- adjust
- priority
- setprio
renice changes the priority of an already running process. Lower values make a process more CPU-prioritized.
System admins use it to ensure critical tasks get more compute resources than background jobs.
Correct Answer: renice
Example Code
sudo renice -n -5 -p 3456
24. Explain the three types of file permissions in Linux.
Difficulty: MediumType: SubjectiveTopic: File Permissions
Linux permissions are divided into read (r), write (w), and execute (x).
Read allows viewing file contents, write allows modifications, and execute lets you run the file if it’s a program or script. Each type applies separately to owner, group, and others.
25. Differentiate between sudo and su commands.
Difficulty: MediumType: SubjectiveTopic: Privilege Escalation
The sudo command executes a single command with superuser privileges, while su switches the current shell to another user (often root).
sudo is safer because it logs activity and limits scope, whereas su grants a full privileged shell.
26. Describe the lifecycle of a Linux process.
Difficulty: MediumType: SubjectiveTopic: Process Basics
A process in Linux goes through several states — created, running, waiting, and terminated.
When a process ends, it becomes a 'zombie' until its parent collects its exit status. Orphaned processes get adopted by the init system.
27. How can you run a command in the background and bring it back to the foreground?
Difficulty: EasyType: SubjectiveTopic: Job Control
Appending an ampersand (&) after a command runs it in the background, freeing the terminal.
To bring it back, use the fg command followed by its job number. You can check job numbers using jobs.
Example Code
sleep 60 &
jobs
fg %1
28. How do you add a user to a specific group in Linux?
Difficulty: MediumType: SubjectiveTopic: Group Management
You can add a user to a group using the usermod command with the -aG option.
This ensures the user gets additional group permissions without removing existing ones. It’s common when granting sudo or docker access.
Example Code
sudo usermod -aG sudo vipul
29. What is the purpose of the first line '#!/bin/bash' in a shell script?
Difficulty: EasyType: MCQTopic: Shell Scripting
- It adds comments to the script
- It tells the system which interpreter to use
- It sets environment variables
- It defines script permissions
The line '#!/bin/bash' is known as a shebang. It instructs the operating system to use the Bash shell to interpret the script.
Without it, the system may use a different default shell, which could cause compatibility issues.
Correct Answer: It tells the system which interpreter to use
30. Which is the correct way to define a variable in Bash?
Difficulty: EasyType: MCQTopic: Shell Variables
- var = 10
- var=10
- $var=10
- define var 10
In Bash, variables are declared without spaces around the equal sign.
To use a variable later, prefix it with a dollar sign — for example, echo $var.
Correct Answer: var=10
Example Code
name=Vipul
echo $name
31. Which command reads user input into a variable?
Difficulty: MediumType: MCQTopic: Shell Scripting
The read command takes user input and stores it in a variable.
You can use the -p flag to display a prompt before reading the input.
Correct Answer: read
Example Code
read -p 'Enter your name: ' username
32. What is the correct syntax for an if statement in Bash?
Difficulty: MediumType: MCQTopic: Conditional Logic
- if(condition) then
- if [ condition ]; then
- if { condition } then
- if (condition);
In Bash, conditions are enclosed in square brackets with spaces around them.
After then, you write the commands to execute if the condition is true, followed by fi to end the block.
Correct Answer: if [ condition ]; then
Example Code
if [ $age -gt 18 ]; then
echo 'Adult'
fi
33. Which syntax correctly defines a for loop in Bash?
Difficulty: MediumType: MCQTopic: Shell Loops
- for (i=0; i<5; i++)
- for i in 1 2 3 4 5; do ... done
- for i=1 to 5 do
- for each i from 1 to 5
Bash loops iterate over lists or sequences using the for-in-do-done structure.
It can also use command substitution like for file in *.log; do echo $file; done.
Correct Answer: for i in 1 2 3 4 5; do ... done
Example Code
for i in 1 2 3 4 5; do
echo $i
done
34. Which of the following executes until a condition becomes false?
Difficulty: MediumType: MCQTopic: Shell Loops
- for loop
- case statement
- while loop
- if block
A while loop keeps executing as long as the test condition is true.
It is commonly used for reading files line by line or running background checks.
Correct Answer: while loop
Example Code
while [ $count -le 5 ]; do
echo $count
((count++))
done
35. Which keyword ends a case statement in Bash?
Difficulty: MediumType: MCQTopic: Case Statement
The case statement in Bash ends with the keyword 'esac', which is 'case' spelled backward.
It’s used for multi-branch conditions similar to switch-case in other programming languages.
Correct Answer: esac
Example Code
case $option in
1) echo 'Start';;
2) echo 'Stop';;
*) echo 'Invalid';;
esac
36. Which variable stores the exit status of the last executed command?
Difficulty: MediumType: MCQTopic: Exit Status
The special variable $? holds the exit status of the most recent command.
A value of 0 means success, while any non-zero value indicates an error or failure.
Correct Answer: $?
Example Code
cp file.txt /backup/
echo $?
37. Which keyword defines a function in a shell script?
Difficulty: MediumType: MCQTopic: Shell Functions
Functions in shell scripts are defined using the function keyword or simply the function name followed by parentheses.
They help group reusable code blocks and make scripts modular.
Correct Answer: function
Example Code
function greet() {
echo 'Hello User'
}
greet38. How is arithmetic performed in shell scripting?
Difficulty: MediumType: SubjectiveTopic: Shell Operators
Arithmetic can be done using double parentheses (( )), expr, or the let command.
For example, result=$((a + b)) is preferred because it’s concise and supports multiple operators without needing escape characters.
Example Code
a=5; b=10; sum=$((a + b)); echo $sum
39. How do you check if a string is empty or not in Bash?
Difficulty: MediumType: SubjectiveTopic: Shell Operators
You can use the -z flag to test if a string is empty and -n to test if it’s not.
Conditional checks like if [ -z "$name" ]; then echo 'Empty'; fi help control program flow based on user input.
Example Code
if [ -z "$input" ]; then
echo 'Empty'
fi
40. Explain two ways to execute a shell script.
Difficulty: MediumType: SubjectiveTopic: Shell Scripting
You can execute a script by running bash scriptname.sh, which starts a new shell.
Alternatively, make it executable using chmod +x scriptname.sh and run it directly with ./scriptname.sh from the terminal.
Example Code
chmod +x deploy.sh
./deploy.sh
41. Give an example of a real use case for loops in automation.
Difficulty: MediumType: SubjectiveTopic: Shell Loops
Loops are widely used in DevOps for log monitoring, batch file renaming, or deployment verification.
For instance, a for loop can iterate over multiple servers to check service availability automatically.
Example Code
for host in server1 server2; do
ping -c 1 $host
done
42. Describe a practical scenario where if-else is used in a deployment script.
Difficulty: MediumType: SubjectiveTopic: Conditional Logic
If-else statements help control execution flow based on conditions. For example, checking if a service is running before restarting it.
This prevents unnecessary downtime or duplicate operations in automation scripts.
Example Code
if systemctl is-active --quiet nginx; then
echo 'Nginx is running'
else
systemctl start nginx
fi
43. Which command is used to schedule tasks to run automatically at specific intervals?
Difficulty: MediumType: MCQTopic: Cron Jobs
The cron daemon runs scheduled commands defined in crontab files.
It is used for automating backups, reports, and maintenance tasks at fixed times or dates.
Correct Answer: cron
Example Code
crontab -e
0 2 * * * /home/user/backup.sh
44. Which command lists all cron jobs for the current user?
Difficulty: EasyType: MCQTopic: Cron Jobs
- cron -l
- crontab -l
- showcron
- ls /etc/cron
crontab -l lists all scheduled cron jobs for the logged-in user.
It’s useful for verifying active automation tasks or debugging missed schedules.
Correct Answer: crontab -l
45. Which command runs a one-time task at a specific time in Linux?
Difficulty: MediumType: MCQTopic: Job Scheduling
The at command is used to execute a command once at a specified time.
Unlike cron, it is not repetitive and is perfect for temporary or one-time jobs.
Correct Answer: at
Example Code
echo 'ls /tmp' | at 11:30
46. What is the difference between '&&' and ';' when chaining commands?
Difficulty: MediumType: MCQTopic: Command Chaining
- They behave the same
- && runs next only if previous succeeds, while ; runs all commands
- ; runs next only if previous succeeds, && runs all commands
- Both are used for background processes
The && operator executes the next command only if the previous one succeeded.
The semicolon (;) executes all commands sequentially, regardless of success or failure.
Correct Answer: && runs next only if previous succeeds, while ; runs all commands
Example Code
mkdir logs && cd logs
47. Which symbol runs a command in the background?
Difficulty: EasyType: MCQTopic: Job Control
Appending an ampersand (&) at the end of a command executes it in the background.
This frees the terminal and allows multiple commands to run simultaneously.
Correct Answer: &
Example Code
sh long_script.sh &
48. What does '>>' do in shell redirection?
Difficulty: MediumType: MCQTopic: Pipes Redirects
- Overwrites a file
- Appends output to an existing file
- Deletes a file before writing
- Reads input from a file
The >> operator appends command output to a file without overwriting its contents.
This is often used in logging to maintain persistent records.
Correct Answer: Appends output to an existing file
Example Code
echo 'Backup complete' >> backup.log
49. Which command combination finds and counts lines matching 'error' in a log file?
Difficulty: MediumType: MCQTopic: Grep Regex
- grep error logfile
- grep -n error logfile
- grep -c error logfile
- grep -r error logfile
The -c flag in grep counts matching lines instead of printing them.
This helps quickly check how many errors or warnings are present in a log file.
Correct Answer: grep -c error logfile
Example Code
grep -c error /var/log/syslog
50. Which utility manages automatic log rotation and compression?
Difficulty: MediumType: MCQTopic: Journalctl Logs
- logrotate
- gzip
- rotate
- syslogd
logrotate automatically rotates, compresses, and deletes old logs to prevent disk overuse.
It’s configured using /etc/logrotate.conf and is essential for server maintenance.
Correct Answer: logrotate
51. How can you pass and access command-line arguments in a shell script?
Difficulty: MediumType: SubjectiveTopic: Shell Parameters
Arguments are passed after the script name and accessed using positional parameters like $1, $2, and so on.
$0 refers to the script name, and $# gives the total count of arguments.
Example Code
echo 'First argument:' $1
echo 'Total args:' $#
52. How do you handle errors gracefully in automation scripts?
Difficulty: MediumType: SubjectiveTopic: Script Debugging
You can check the exit status of each command using $? and use if conditions to act on failures.
Adding set -e at the top stops script execution immediately when a command fails, ensuring predictable automation.
Example Code
set -e
cp data.txt /backup/ || echo 'Backup failed'
53. Explain the five fields in a crontab schedule expression.
Difficulty: MediumType: SubjectiveTopic: Cron Jobs
Crontab syntax uses five fields: minute, hour, day of month, month, and day of week.
For example, 0 3 * * 1 means run every Monday at 3 AM. Using */5 in a field sets the command to repeat every 5 units.
Example Code
0 3 * * 1 /scripts/cleanup.sh
54. How do you log output from a shell script for future reference?
Difficulty: MediumType: SubjectiveTopic: Journalctl Logs
You can redirect both standard output and error to a log file using > and 2> operators.
For example, script.sh > output.log 2>&1 saves all messages, making debugging easier later.
Example Code
./deploy.sh > deploy.log 2>&1
55. Describe how you would automate a daily file backup using cron.
Difficulty: MediumType: SubjectiveTopic: Task Automation
First, write a shell script that copies important files to a backup directory with a timestamp.
Then, schedule it in crontab to run every night using a 0 2 * * * entry for 2 AM backups.
Example Code
0 2 * * * /home/admin/backup.sh
56. Give a real-world example of using pipes for automation.
Difficulty: MediumType: SubjectiveTopic: Pipes Redirects
Pipes can chain multiple commands together for automation. For instance, you can filter and email only failed log entries.
Example: grep 'FAILED' app.log | mail -s 'Daily Errors' admin@domain.com.
Example Code
grep 'FAILED' app.log | mail -s 'Daily Errors' admin@domain.com
57. Which command shows how long the system has been running and the average load?
Difficulty: EasyType: MCQTopic: System Monitoring
The uptime command displays the current time, system uptime, number of logged-in users, and the system load averages.
It helps assess whether the machine is under heavy load or has been running continuously.
Correct Answer: uptime
58. Which command displays disk usage information for mounted filesystems?
Difficulty: EasyType: MCQTopic: Disk Usage
The df command (disk free) shows available and used disk space for each mounted filesystem.
Adding -h makes the output human-readable, showing sizes in MB or GB.
Correct Answer: df
59. What does the 'du' command report?
Difficulty: MediumType: MCQTopic: Disk Usage
- Disk space usage of files and directories
- CPU utilization
- Memory usage
- Network connections
du (disk usage) estimates the file space used by directories.
It’s often paired with sort and head to identify the largest directories consuming disk space.
Correct Answer: Disk space usage of files and directories
Example Code
du -sh * | sort -rh | head -10
60. Which command displays memory and swap usage in Linux?
Difficulty: MediumType: MCQTopic: System Monitoring
The free command shows total, used, and available memory including swap space.
The -m or -h flag can display values in megabytes or human-readable format.
Correct Answer: free
61. Which command lists active network connections and ports?
Difficulty: MediumType: MCQTopic: Network Diagnostics
- ping
- ip a
- netstat -tuln
- route
netstat shows open ports, listening services, and active connections.
Options like -tuln display TCP/UDP sockets numerically without DNS lookups, helping identify which ports are in use.
Correct Answer: netstat -tuln
Example Code
netstat -tuln
62. What does the 'ping' command test?
Difficulty: EasyType: MCQTopic: Network Diagnostics
- DNS records
- Network latency and connectivity
- Firewall rules
- Routing tables
ping sends ICMP echo requests to a host to check if it’s reachable and measures round-trip latency.
It’s one of the first commands used for basic network troubleshooting.
Correct Answer: Network latency and connectivity
Example Code
ping google.com
63. Which command displays the path packets take to reach a destination host?
Difficulty: MediumType: MCQTopic: Network Diagnostics
- netpath
- tracepath
- traceroute
- pathfind
traceroute traces each hop packets pass through to reach a target.
It’s useful for identifying where network delays or failures occur.
Correct Answer: traceroute
Example Code
traceroute 8.8.8.8
64. Which option of the 'tail' command follows log updates in real time?
Difficulty: MediumType: MCQTopic: File Viewing
Using tail -f continuously outputs new lines added to a file.
It’s commonly used to monitor live logs like nginx or system logs while debugging.
Correct Answer: -f
Example Code
tail -f /var/log/syslog
65. Which command displays logs from the systemd journal?
Difficulty: MediumType: MCQTopic: Journalctl Logs
- logcat
- journalctl
- syslog
- cat /var/log/messages
journalctl queries and displays logs collected by systemd.
Options like -u specify a unit, and -f follows logs in real time similar to tail.
Correct Answer: journalctl
Example Code
journalctl -u nginx -f
66. How do you identify which process is consuming the most CPU and memory?
Difficulty: MediumType: SubjectiveTopic: System Monitoring
Use top or htop to monitor real-time CPU and memory usage.
Sort by CPU or memory to identify heavy processes. You can also use ps aux --sort=-%mem | head to list the top memory consumers.
Example Code
ps aux --sort=-%cpu | head
67. Describe the steps to troubleshoot network connectivity in Linux.
Difficulty: MediumType: SubjectiveTopic: Network Diagnostics
Start by checking link status with ip a or ifconfig, then test reachability using ping.
Next, check DNS with dig or nslookup, and use traceroute to find where packets drop. If still unresolved, verify firewall rules with ufw or iptables.
Example Code
ping 8.8.8.8
traceroute google.com
68. How do you identify which directories are using the most disk space?
Difficulty: MediumType: SubjectiveTopic: Disk Management
The du command is used to measure disk usage recursively.
Combine it with sort to list directories from largest to smallest, helping clean up space efficiently.
Example Code
du -h --max-depth=1 /var | sort -hr | head
69. Explain how to analyze application logs for errors or warnings.
Difficulty: MediumType: SubjectiveTopic: Journalctl Logs
Use grep to search for keywords like ERROR or WARNING in log files.
Combine with tail -f for real-time tracking during deployments or troubleshooting.
Example Code
grep 'ERROR' /var/log/app.log | tail -n 20
70. How can you find which process is listening on a specific port?
Difficulty: MediumType: SubjectiveTopic: Network Diagnostics
Use netstat -tulnp or ss -tulnp to list active ports and their associated process IDs.
Alternatively, lsof -i :PORT_NUMBER shows which process is bound to that port, helping debug port conflicts.
Example Code
sudo lsof -i :8080
71. Which command installs a package using the APT package manager?
Difficulty: EasyType: MCQTopic: Package Management
- apt install
- apt-get run
- yum install
- pkg add
APT (Advanced Package Tool) is used on Debian-based systems like Ubuntu to install, remove, and update packages.
The command apt install <package_name> downloads and installs the package along with dependencies.
Correct Answer: apt install
Example Code
sudo apt install nginx -y
72. Which command installs packages on Red Hat or CentOS systems?
Difficulty: EasyType: MCQTopic: Package Management
- yum install
- dnf add
- apt install
- pkg get
yum (Yellowdog Updater Modified) is used for package management on Red Hat-based systems.
It handles installation, dependency resolution, and updates automatically.
Correct Answer: yum install
Example Code
sudo yum install httpd -y
73. What does the dpkg command do in Debian-based systems?
Difficulty: MediumType: MCQTopic: Package Management
- Compiles source packages
- Manages low-level .deb package installations
- Updates repositories
- Lists available packages online
dpkg installs or removes .deb files manually without fetching from repositories.
It’s often used for troubleshooting or offline installations when APT is not available.
Correct Answer: Manages low-level .deb package installations
Example Code
sudo dpkg -i package.deb
74. Which command starts a service using systemd?
Difficulty: EasyType: MCQTopic: Service Management
- service start nginx
- systemctl start nginx
- systemctl run nginx
- init.d start nginx
systemctl is the primary command to manage services on systems using systemd.
You can start, stop, enable, or check the status of services using it.
Correct Answer: systemctl start nginx
Example Code
sudo systemctl start nginx
75. Which command ensures a service starts automatically on boot?
Difficulty: MediumType: MCQTopic: Service Management
- systemctl enable
- systemctl boot
- service autostart
- initctl start
systemctl enable creates a symbolic link in the system startup directories.
It ensures the service automatically starts during system boot without manual execution.
Correct Answer: systemctl enable
Example Code
sudo systemctl enable docker
76. Which systemctl command checks the current status of a service?
Difficulty: EasyType: MCQTopic: Service Management
- systemctl info nginx
- systemctl status nginx
- service check nginx
- systemctl active nginx
systemctl status displays whether a service is active, inactive, or failed.
It also shows logs from the systemd journal, helping quickly diagnose service issues.
Correct Answer: systemctl status nginx
Example Code
sudo systemctl status nginx
77. Which command restarts a running service?
Difficulty: MediumType: MCQTopic: Service Management
- service reload nginx
- systemctl restart nginx
- systemctl reload nginx
- restart nginx
systemctl restart stops and then starts a service again.
It’s used to apply new configurations or recover from temporary failures.
Correct Answer: systemctl restart nginx
Example Code
sudo systemctl restart nginx
78. What is the difference between 'systemctl restart' and 'systemctl reload'?
Difficulty: MediumType: MCQTopic: Service Management
- restart reboots systemd, reload shuts down services
- restart reloads config without downtime
- restart stops and starts service, reload applies new configs without stopping
- both are identical commands
reload signals the service to re-read configuration files without a full restart.
This reduces downtime, making it ideal for web or database servers where uptime is critical.
Correct Answer: restart stops and starts service, reload applies new configs without stopping
Example Code
sudo systemctl reload nginx
79. Which command shows service logs managed by systemd?
Difficulty: MediumType: MCQTopic: Journalctl Logs
- syslogctl
- journalctl -u servicename
- logview servicename
- tail /var/log/service.log
journalctl is part of systemd and displays log entries collected by it.
Use -u followed by the service name to see logs specific to that unit, and -f to follow in real time.
Correct Answer: journalctl -u servicename
Example Code
journalctl -u ssh -f
80. How do you update all system packages safely in Linux?
Difficulty: MediumType: SubjectiveTopic: Package Management
On Debian systems, use apt update to refresh the package index, then apt upgrade to install new versions.
On RHEL or CentOS, use yum update. Always run updates with sudo to apply them system-wide.
Example Code
sudo apt update && sudo apt upgrade -y
81. How do you debug a service that fails to start using systemd?
Difficulty: MediumType: SubjectiveTopic: Service Management
Start by checking the service status with systemctl status servicename.
Then use journalctl -u servicename to review detailed logs and identify errors. Fix missing dependencies or configuration syntax errors accordingly.
Example Code
systemctl status nginx
journalctl -u nginx
82. How can you safely remove a package along with unused dependencies?
Difficulty: MediumType: SubjectiveTopic: Package Management
Use apt autoremove or yum autoremove depending on the system. This removes the specified package and related libraries not used by others.
It helps keep servers lean and avoids unnecessary storage usage.
Example Code
sudo apt remove nginx -y && sudo apt autoremove -y
83. Explain how to verify which services start automatically at boot.
Difficulty: MediumType: SubjectiveTopic: Service Management
Use systemctl list-unit-files --type=service to see which units are enabled or disabled.
You can also run systemctl is-enabled servicename to check the startup behavior of a specific service.
Example Code
systemctl list-unit-files --type=service | grep enabled
84. What are systemd unit files, and where are they stored?
Difficulty: MediumType: SubjectiveTopic: Service Management
Unit files define how systemd manages services, sockets, targets, and timers.
They are stored under /etc/systemd/system for custom services and /lib/systemd/system for system-managed ones.
Example Code
/etc/systemd/system/myapp.service
85. Which command displays all network interfaces and their IP addresses?
Difficulty: EasyType: MCQTopic: Networking Basics
- netstat -a
- ip a
- ifup
- route -n
The ip a command lists all network interfaces, their assigned IP addresses, and their operational states.
It replaces older tools like ifconfig in modern Linux systems.
Correct Answer: ip a
86. Which command checks basic network connectivity between two systems?
Difficulty: EasyType: MCQTopic: Network Diagnostics
ping sends ICMP echo requests to a host and waits for replies.
It’s used to verify that a host is reachable and to measure round-trip network latency.
Correct Answer: ping
87. Which command displays or sets the system hostname?
Difficulty: EasyType: MCQTopic: Networking Basics
- hostctl
- hostnamectl
- hostconfig
- sysname
hostnamectl is used to view and change the system hostname.
It’s part of systemd and also shows OS information and kernel details.
Correct Answer: hostnamectl
Example Code
sudo hostnamectl set-hostname dev-server
88. Which command enables the uncomplicated firewall (UFW) on Ubuntu?
Difficulty: MediumType: MCQTopic: UFW Firewall
- firewalld --enable
- ufw enable
- iptables on
- systemctl start ufw
UFW (Uncomplicated Firewall) is a frontend for iptables that simplifies firewall configuration.
The command ufw enable activates it with the default rules.
Correct Answer: ufw enable
Example Code
sudo ufw enable
89. How do you allow SSH connections through UFW?
Difficulty: MediumType: MCQTopic: UFW Firewall
- ufw allow port 22
- ufw allow ssh
- ufw permit sshd
- iptables -A INPUT ssh
The command ufw allow ssh opens port 22 for inbound SSH connections.
You can also specify the protocol and IP range for more precise access control.
Correct Answer: ufw allow ssh
Example Code
sudo ufw allow ssh
90. Which command lists all current firewall rules in iptables?
Difficulty: MediumType: MCQTopic: Iptables Firewall
- iptables -L
- iptables -show
- firewall list
- netstat -f
iptables -L displays all firewall rules applied to INPUT, OUTPUT, and FORWARD chains.
It’s used for fine-grained control over packets and ports.
Correct Answer: iptables -L
Example Code
sudo iptables -L -v -n
91. Which command connects to a remote Linux machine using SSH?
Difficulty: EasyType: MCQTopic: SSH Command
SSH (Secure Shell) connects securely to remote systems over the network.
It encrypts both authentication and data transfer to protect communication from eavesdropping.
Correct Answer: ssh
Example Code
ssh user@192.168.1.10
92. Which command generates SSH key pairs for passwordless login?
Difficulty: MediumType: MCQTopic: SSH Command
- ssh -keygen
- ssh-keygen
- keygen ssh
- gen-key ssh
ssh-keygen creates public and private SSH keys for secure, passwordless authentication.
The generated keys are stored by default under ~/.ssh directory.
Correct Answer: ssh-keygen
Example Code
ssh-keygen -t rsa -b 4096
93. Which command securely copies files between remote systems over SSH?
Difficulty: MediumType: MCQTopic: File Transfer
scp (secure copy) transfers files between hosts securely using the SSH protocol.
It’s simple and encrypted, making it ideal for server-to-server data transfers.
Correct Answer: scp
Example Code
scp file.txt user@server:/tmp/
94. Where is the SSH client configuration file located, and what is it used for?
Difficulty: MediumType: SubjectiveTopic: SSH Command
The SSH client configuration file is located at ~/.ssh/config for user-specific settings or /etc/ssh/ssh_config for system-wide settings.
It’s used to define connection parameters like hostname, user, port, and identity file for easy and repeatable access.
Example Code
Host myserver
HostName 192.168.1.20
User ubuntu
IdentityFile ~/.ssh/id_rsa
95. What are best practices for securing SSH access on production servers?
Difficulty: MediumType: SubjectiveTopic: SSH Security
Disable root login by setting PermitRootLogin no in sshd_config. Use SSH keys instead of passwords.
Change the default port, restrict users with AllowUsers, and enable firewall rules to allow only trusted IPs.
Example Code
sudo vi /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
96. How do you view, add, and delete firewall rules using UFW?
Difficulty: MediumType: SubjectiveTopic: Firewall Tools
Use ufw status numbered to list all active rules with indexes.
To remove a rule, run ufw delete <rule_number>. You can add rules with ufw allow or ufw deny for specific ports or services.
Example Code
sudo ufw status numbered
sudo ufw delete 2
97. How can you verify if a remote port is open using the command line?
Difficulty: MediumType: SubjectiveTopic: Network Diagnostics
Use telnet or nc (netcat) to check connectivity to a remote port.
If the port is open, the connection succeeds; otherwise, it times out. It’s often used to verify database or API endpoint availability.
Example Code
nc -zv 192.168.1.50 22
98. Describe how to troubleshoot SSH connection issues.
Difficulty: MediumType: SubjectiveTopic: SSH Command
First, check network reachability using ping and confirm port 22 is open.
Then verify sshd service is running, review /var/log/auth.log for errors, and ensure the public key is correctly copied in ~/.ssh/authorized_keys.
Example Code
systemctl status ssh
cat /var/log/auth.log
99. Which command lists all available block devices like disks and partitions?
Difficulty: EasyType: MCQTopic: Disk Management
lsblk shows information about all storage devices such as disks, partitions, and mount points.
It’s a quick way to check attached drives and where they are mounted.
Correct Answer: lsblk
100. Which command is used to mount a filesystem to a directory?
Difficulty: EasyType: MCQTopic: Mount Management
The mount command attaches a filesystem to a specific directory so its data becomes accessible.
Unmount it later using umount when no longer needed.
Correct Answer: mount
Example Code
sudo mount /dev/sdb1 /mnt/data
101. Which command detaches a mounted filesystem safely?
Difficulty: EasyType: MCQTopic: Mount Management
- unmount
- umount
- detach
- remount
umount safely detaches a mounted filesystem.
Always close open files and change directories before unmounting to avoid data loss.
Correct Answer: umount
Example Code
sudo umount /mnt/data
102. What does the 'df -h' command display?
Difficulty: MediumType: MCQTopic: Disk Usage
- File permissions
- Disk space usage by mounted filesystems
- Folder structure
- File size in bytes
df -h (disk free) shows available and used space for each mounted filesystem.
The -h option formats the output in human-readable units like MB or GB.
Correct Answer: Disk space usage by mounted filesystems
103. Which command shows disk space used by directories and files?
Difficulty: MediumType: MCQTopic: Disk Usage
du (disk usage) displays the size of directories and files recursively.
It’s helpful to locate which directories consume the most disk space.
Correct Answer: du
Example Code
du -sh * | sort -rh | head
104. Which command creates an archive file from multiple files or directories?
Difficulty: MediumType: MCQTopic: Archiving Tools
tar is used to group multiple files or directories into one archive file.
It’s often used with gzip for compressed backups, using the -czf option.
Correct Answer: tar
Example Code
tar -czf backup.tar.gz /home/user/
105. Which command compresses files using GNU zip?
Difficulty: MediumType: MCQTopic: Archiving Tools
gzip compresses files efficiently to save space.
Use gunzip or gzip -d to decompress them when needed.
Correct Answer: gzip
Example Code
gzip largefile.log
106. Which command synchronizes files and directories between systems?
Difficulty: MediumType: MCQTopic: Backup Restore
rsync transfers files locally or between remote systems efficiently.
It copies only changed parts, making it ideal for backups and incremental syncs.
Correct Answer: rsync
Example Code
rsync -av /data /backup/
107. What is the purpose of the /etc/fstab file?
Difficulty: MediumType: MCQTopic: Mount Management
- Defines firewall rules
- Lists scheduled tasks
- Lists filesystems to mount automatically on boot
- Tracks user login sessions
The /etc/fstab file contains entries for all filesystems that should mount automatically during boot.
Each line specifies the device, mount point, filesystem type, and mount options.
Correct Answer: Lists filesystems to mount automatically on boot
Example Code
/dev/sdb1 /mnt/data ext4 defaults 0 2
108. How do you mount a drive permanently in Linux?
Difficulty: MediumType: SubjectiveTopic: Mount Management
First, identify the drive using lsblk or blkid and note its UUID.
Then add an entry in /etc/fstab specifying the UUID, mount point, and filesystem type. Run mount -a to verify before rebooting.
Example Code
UUID=abcd-1234 /mnt/data ext4 defaults 0 2
109. Describe a basic backup strategy for a Linux production server.
Difficulty: MediumType: SubjectiveTopic: Backup Restore
Use rsync or tar to perform daily backups of key directories like /etc, /home, and /var.
Automate the process with cron and store backups on an external drive or remote storage. Always test restore procedures regularly.
Example Code
rsync -av /var/www /backup/webdata/
110. How do you restore files from a tar backup?
Difficulty: MediumType: SubjectiveTopic: Backup Restore
Use the tar -xzf command followed by the backup filename to extract files.
You can specify -C to choose a target directory for extraction. Always check file permissions after restore.
Example Code
tar -xzf backup.tar.gz -C /restore/
111. How can you check the health and SMART status of a disk?
Difficulty: MediumType: SubjectiveTopic: Disk Management
Use the smartctl command from the smartmontools package to view detailed disk health information.
It reports temperature, bad sectors, and performance warnings, helping detect failing drives early.
Example Code
sudo smartctl -a /dev/sda
112. How do you identify and clean large unnecessary files consuming disk space?
Difficulty: MediumType: SubjectiveTopic: Disk Management
Use du and find commands to locate large files, then manually delete or archive them.
You can automate this cleanup using a shell script scheduled via cron for periodic maintenance.
Example Code
find / -type f -size +500M -exec ls -lh {} \;113. Which command lists running processes for the current user?
Difficulty: EasyType: MCQTopic: Process Monitoring
The ps command shows currently running processes along with their process IDs.
You can use options like ps aux to view all system processes.
Correct Answer: ps
114. Which command displays a real-time view of CPU and memory usage?
Difficulty: EasyType: MCQTopic: Process Monitoring
top displays real-time system performance, including CPU, memory, and process statistics.
It’s useful for identifying high-load processes quickly.
Correct Answer: top
115. Which command is an interactive, color-enhanced alternative to top?
Difficulty: MediumType: MCQTopic: Process Monitoring
htop provides an improved, interactive interface to monitor system resources.
You can scroll, search, and kill processes directly from within the UI.
Correct Answer: htop
116. Which command terminates a process using its PID?
Difficulty: MediumType: MCQTopic: Process Signals
The kill command sends a signal to a process to terminate it.
Use kill -9 for forceful termination when normal kill fails.
Correct Answer: kill
117. Which command adjusts the priority of a process at start?
Difficulty: MediumType: MCQTopic: Process Priority
The nice command launches a process with a specific priority value.
Lower nice values mean higher priority; positive values reduce CPU priority.
Correct Answer: nice
Example Code
nice -n 10 ./backup.sh
118. Which command changes the priority of an already running process?
Difficulty: MediumType: MCQTopic: Process Priority
- nice
- renice
- prioedit
- setprio
renice adjusts the niceness (priority) of running processes.
It helps control CPU scheduling dynamically during runtime.
Correct Answer: renice
Example Code
sudo renice +5 -p 4567
119. Which commands resume a suspended process in the background or foreground?
Difficulty: MediumType: MCQTopic: Job Control
- start/resume
- bg/fg
- open/close
- run/wait
bg resumes a stopped job in the background, while fg brings it back to the foreground.
They are used in interactive shell sessions to manage job execution.
Correct Answer: bg/fg
120. Which command edits scheduled recurring jobs for the current user?
Difficulty: MediumType: MCQTopic: Cron Jobs
- schedule -e
- cronjob -e
- crontab -e
- editcron
crontab -e opens the user’s cron table for editing recurring job schedules.
Each line defines when and how often a command runs automatically.
Correct Answer: crontab -e
Example Code
crontab -e
0 2 * * * /scripts/backup.sh
121. Which command schedules a one-time job to run later?
Difficulty: MediumType: MCQTopic: Job Scheduling
The at command runs a command once at a specific future time.
It’s useful for delayed tasks like log rotation or temporary file cleanup.
Correct Answer: at
Example Code
echo 'rm /tmp/tempfile' | at 3:00 AM
122. How can you list and manage background jobs in a shell session?
Difficulty: MediumType: SubjectiveTopic: Job Control
Use the jobs command to list all background or stopped processes in the current shell.
Bring one back to the foreground using fg %job_number or resume it in the background using bg %job_number.
123. Explain the five fields of a cron job expression.
Difficulty: MediumType: SubjectiveTopic: Cron Jobs
A cron expression has five fields: minute, hour, day of month, month, and day of week.
For example, 0 3 * * 1 means run every Monday at 3 AM. Use @daily or @reboot for predefined schedules.
Example Code
0 3 * * 1 /scripts/cleanup.sh
124. How can you monitor a specific process continuously?
Difficulty: MediumType: SubjectiveTopic: Process Monitoring
Use watch with ps or pgrep to refresh process information at regular intervals.
This helps monitor memory usage or uptime of critical processes.
Example Code
watch -n 2 'ps -C nginx -o pid,cmd,%mem,%cpu'
125. How do you log the output of cron jobs for debugging?
Difficulty: MediumType: SubjectiveTopic: Script Logging
Redirect both standard output and error streams to a log file in the cron entry.
This ensures any issues during execution are captured for analysis.
Example Code
0 2 * * * /scripts/backup.sh > /var/log/backup.log 2>&1
126. Describe a simple automation example using cron or at commands.
Difficulty: MediumType: SubjectiveTopic: Task Automation
You can automate database backups daily using cron.
For instance, schedule a cron job to run a MySQL dump script at midnight and store it with a timestamp for versioned backups.
Example Code
0 0 * * * /scripts/mysql_backup.sh
127. What is Linux?
Difficulty: EasyType: MCQTopic: Filesystem Basics
- An open-source Unix-like operating system kernel
- A programming language
- A database management system
- A web server
Linux is an open-source Unix-like operating system kernel originally created by Linus Torvalds in 1991. It forms the core of various Linux distributions (distros) like Ubuntu, CentOS, Debian, and Red Hat. The kernel manages hardware resources, processes, memory, and provides a foundation for applications to run on.
Linux is known for its stability, security, and flexibility, making it the dominant operating system for servers, cloud infrastructure, embedded systems, and increasingly for desktop computing. Unlike proprietary operating systems, Linux's open-source nature allows anyone to view, modify, and distribute the source code.
Linux follows the Unix philosophy of small, modular tools that work together. It's used by major tech companies like Google, Amazon, Facebook, and Netflix for their infrastructure. Understanding Linux is fundamental for DevOps, system administration, cloud computing, and backend development careers.
Correct Answer: An open-source Unix-like operating system kernel
128. What is stored in the /etc directory in Linux?
Difficulty: EasyType: MCQTopic: Filesystem Basics
- System configuration files
- User home directories
- Temporary files
- Binary executables
The /etc directory contains system-wide configuration files and scripts used by the operating system and applications. Important files include /etc/passwd (user accounts), /etc/shadow (encrypted passwords), /etc/group (group information), /etc/hosts (hostname to IP mapping), and /etc/fstab (filesystem mount points).
Configuration files in /etc are typically plain text files that can be edited with text editors like vi, nano, or vim. Changes to files in /etc usually require root privileges since they affect system-wide behavior. Many applications store their configuration in subdirectories under /etc.
Understanding /etc is crucial for system administration as it's where you configure network settings, user permissions, system services, and application behavior. Common tasks include editing /etc/ssh/sshd_config for SSH settings, /etc/network/interfaces for networking, or /etc/crontab for scheduled tasks.
Correct Answer: System configuration files
129. What does the command 'chmod 755 file.sh' do?
Difficulty: MediumType: MCQTopic: File Permissions
- Sets read, write, execute for owner; read and execute for group and others
- Sets all permissions for everyone
- Removes all permissions
- Sets write permission only
Chmod 755 breaks down as 7 (owner), 5 (group), and 5 (others). Each digit is the sum of permissions: read=4, write=2, execute=1. So 7=4+2+1 (rwx for owner), 5=4+1 (r-x for group), and 5=4+1 (r-x for others). This is a common permission set for scripts and executables.
The owner can read, modify, and execute the file, while group members and other users can read and execute but cannot modify it. This permission scheme is typical for shell scripts that need to be executable but shouldn't be modified by non-owners.
Understanding octal notation is essential for Linux administration. Other common permissions include 644 (rw-r--r--) for regular files, 600 (rw-------) for sensitive files like private keys, and 777 (rwxrwxrwx) for fully open files though this is generally insecure and discouraged.
Correct Answer: Sets read, write, execute for owner; read and execute for group and others
130. Which command is used to display the current working directory?
Difficulty: EasyType: MCQTopic: Linux Commands
The pwd (print working directory) command displays the full path of your current location in the filesystem. It's one of the most basic navigation commands and helps you understand where you are in the directory structure, especially useful when working with absolute and relative paths.
Pwd is particularly helpful in shell scripts to ensure you're in the correct directory before executing commands, or when navigating complex directory structures. It takes no arguments in its basic form and simply outputs the current directory path.
Related commands include cd (change directory) for navigation, ls (list) for viewing directory contents, and dirs for displaying the directory stack. Understanding pwd is fundamental for command-line navigation and is often one of the first commands taught to Linux beginners.
Correct Answer: pwd
131. What is the difference between a hard link and a symbolic link?
Difficulty: MediumType: MCQTopic: Filesystem Basics
- Hard links point to inode, symbolic links point to filename; hard links break if original deleted
- Hard links are slower than symbolic links
- Symbolic links can only link to files in the same directory
- They are exactly the same
Hard links create multiple directory entries pointing to the same inode (actual data on disk). All hard links are equal - deleting one doesn't affect others since they all reference the same data. Hard links cannot span filesystems or link to directories. Create with ln source target.
Symbolic links (symlinks) are special files containing a path to another file or directory. They're like shortcuts - if the original file is deleted, the symlink breaks becoming a dangling pointer. Symlinks can span filesystems and link to directories. Create with ln -s source target.
Use hard links when you need multiple references to the same data that persist even if one reference is deleted. Use symlinks for flexibility, creating shortcuts, or linking across filesystems. Most use cases prefer symlinks due to their flexibility, though hard links have performance advantages for large files since they don't add indirection.
Correct Answer: Hard links point to inode, symbolic links point to filename; hard links break if original deleted
132. In the output of 'ls -l', what does the first character indicate?
Difficulty: MediumType: MCQTopic: Filesystem Basics
- The file type (- for regular file, d for directory, l for link)
- The file size
- The file owner
- The creation date
The first character in ls -l output indicates file type: '-' for regular files, 'd' for directories, 'l' for symbolic links, 'c' for character devices, 'b' for block devices, 'p' for named pipes (FIFOs), and 's' for sockets. This helps quickly identify what kind of file you're dealing with.
Following the file type character are nine permission characters (rwxrwxrwx) representing owner, group, and other permissions. Then comes link count, owner, group, size, modification time, and filename. Understanding this format is essential for interpreting file listings and permissions.
Example: 'drwxr-xr-x' indicates a directory with owner having full permissions, group and others having read and execute. 'lrwxrwxrwx' indicates a symbolic link with permissions (though actual permissions depend on the target file). Knowing file types helps in troubleshooting and system administration tasks.
Correct Answer: The file type (- for regular file, d for directory, l for link)
133. Which command copies files and directories recursively?
Difficulty: EasyType: MCQTopic: File Operations
The cp -r (or cp -R) command copies directories and their contents recursively, including all subdirectories and files. The -r flag stands for recursive and is necessary when copying directories since cp alone only copies files. Without -r, attempting to copy a directory results in an error.
Common cp options include -i for interactive mode (prompting before overwrite), -v for verbose output, -p to preserve file attributes (permissions, timestamps), and -a for archive mode (preserves everything and copies recursively). For example, cp -a source/ destination/ creates an exact copy.
Related commands include mv for moving/renaming files, rm for deletion, and rsync for more advanced copying with features like progress display, partial transfers, and network copying. Understanding cp is fundamental for file management in Linux.
Correct Answer: cp -r
134. Explain the Linux filesystem hierarchy. What are the purposes of /home, /var, /usr, /tmp, and /opt directories?
Difficulty: MediumType: SubjectiveTopic: Filesystem Basics
The /home directory contains user home directories where personal files, documents, and user-specific configurations are stored. Each user typically has a subdirectory like /home/username with their files and settings. This separation keeps user data isolated and makes backups easier.
/var stores variable data that changes during system operation including log files (/var/log), mail spools (/var/mail), print queues, and temporary files that persist across reboots. It's crucial for system monitoring and troubleshooting since application logs accumulate here. /var can grow large so it's often on a separate partition.
/usr contains user programs and data shared across users including /usr/bin for user commands, /usr/lib for libraries, /usr/local for locally installed software, and /usr/share for shared data. Most application binaries and libraries live here. /tmp stores temporary files that may be deleted on reboot, used by applications for transient data. /opt contains optional third-party software packages installed as complete subdirectories.
Understanding the filesystem hierarchy helps with system administration, troubleshooting (knowing where logs are), software installation, and backup strategies. The Filesystem Hierarchy Standard (FHS) defines these conventions ensuring consistency across Linux distributions.
135. Explain Linux file permissions including special permissions (setuid, setgid, sticky bit). How do they work and when are they used?
Difficulty: HardType: SubjectiveTopic: File Permissions
Standard Linux permissions include read (r/4), write (w/2), and execute (x/1) for owner, group, and others. Read allows viewing file contents or listing directory contents. Write allows modifying files or creating/deleting files in directories. Execute allows running files as programs or entering directories.
Special permissions provide additional security control. Setuid (4000 in octal, s in owner execute position) makes executable files run with the owner's privileges rather than the executor's - useful for programs needing elevated privileges like passwd command. Setgid (2000 in octal, s in group execute position) makes executables run with group privileges, or in directories, makes new files inherit the directory's group.
Sticky bit (1000 in octal, t in others execute position) on directories restricts file deletion - only file owners can delete their files even if directory is world-writable. Used on /tmp to prevent users from deleting others' temporary files. Set with chmod +t directory or chmod 1777 directory.
Example permissions: chmod 4755 file sets setuid with standard 755 permissions. chmod 2775 directory sets setgid for group collaboration. Understanding special permissions is crucial for security, multi-user environments, and proper system configuration. Misuse can create security vulnerabilities, so use them carefully.
136. What is an inode in Linux? Explain its structure and how it relates to files and hard links.
Difficulty: HardType: SubjectiveTopic: Filesystem Basics
An inode (index node) is a data structure that stores metadata about a file including permissions, ownership, timestamps, size, and pointers to data blocks containing the file's content. Every file has one inode, but directories map filenames to inode numbers. The filename isn't stored in the inode - it's stored in the directory entry.
Inodes contain file metadata but not the filename or data itself. They include file type, permissions (mode), owner UID, group GID, file size, timestamps (access, modification, change), link count, and pointers to data blocks. You can view inode numbers with ls -i and detailed inode information with stat command.
Hard links create multiple directory entries (filenames) pointing to the same inode. The link count in the inode tracks how many directory entries reference it. When you delete a file, you're removing a directory entry and decrementing the link count. The actual data is only deleted when link count reaches zero and no processes have the file open.
Understanding inodes explains why hard links can't cross filesystems (each filesystem has its own inode table), why directories can't be hard-linked (would create circular references), and how file deletion actually works. The number of available inodes limits how many files you can create regardless of disk space - important for systems with many small files.
137. Explain the differences between cp, mv, and rsync commands. When would you use each?
Difficulty: MediumType: SubjectiveTopic: Linux Commands
The cp command copies files and directories, creating a duplicate while leaving the original intact. Use cp for local copying when you need both source and destination files. Common flags include -r for recursive directory copying, -p to preserve attributes, -i for interactive mode, and -v for verbose output. Cp is simple and sufficient for most local file duplication needs.
The mv command moves or renames files and directories. Unlike cp, it doesn't create a duplicate - it either renames a file (same filesystem) or copies and deletes the original (across filesystems). Use mv when you want to relocate files or change names without duplication. Mv is atomic within the same filesystem, making it safer for moving important files.
Rsync is a powerful tool for copying and synchronizing files locally or remotely over SSH. It uses delta-transfer algorithm, only copying changed portions of files, making it efficient for large files or directories. Rsync can resume interrupted transfers, preserve permissions/timestamps, show progress, and exclude patterns. Use rsync for backups, syncing large datasets, remote copies, or when you need advanced features.
Example: rsync -avz --progress source/ user@remote:/destination/ copies with archive mode, compression, and progress display. Choose cp for simple local copies, mv for relocating files, and rsync for efficient syncing, backups, or remote transfers. Understanding each tool's strengths helps you select the right one for your task.
138. Explain common directory navigation commands and shortcuts in Linux. Include cd, pushd, popd, and special directory references.
Difficulty: EasyType: SubjectiveTopic: Path Navigation
The cd command changes the current directory. cd /path goes to absolute path, cd path goes to relative path, cd without arguments or cd ~ goes to home directory, cd - returns to previous directory (useful for toggling between two directories), and cd .. moves to parent directory. Understanding these shortcuts speeds up navigation significantly.
Pushd and popd maintain a directory stack for navigating between multiple directories. Pushd /path changes to the path and pushes current directory onto the stack. Popd returns to the directory at top of stack. Use dirs to view the stack. This is useful when working in multiple locations and wanting to quickly return.
Special directory references include . (current directory), .. (parent directory), ~ (home directory), / (root directory), and - (previous directory). These work with most commands, like cp file.txt .. to copy to parent directory, or ./script.sh to execute a script in current directory.
Tab completion is essential for efficient navigation - typing cd /ho and pressing Tab completes to /home. Typing cd /home/u then Tab shows options if multiple matches exist. Combine these techniques with history search (Ctrl+R) for maximum efficiency. Mastering navigation is fundamental for productive Linux usage.
139. Explain the find command in Linux. How do you search for files by name, size, modification time, and permissions?
Difficulty: HardType: SubjectiveTopic: File Finding
The find command searches for files and directories based on various criteria. Basic syntax is find [path] [options] [tests] [actions]. For example, find /home -name "*.txt" searches for .txt files in /home. Use -iname for case-insensitive name search. The -name option uses shell patterns (* for any characters, ? for single character).
Search by size with -size: find / -size +100M finds files larger than 100MB. Use +n for greater than, -n for less than, and n for exactly. Units include c (bytes), k (kilobytes), M (megabytes), G (gigabytes). Find by time with -mtime (modified), -atime (accessed), or -ctime (changed): find /var/log -mtime -7 finds files modified in last 7 days.
Search by permissions with -perm: find /home -perm 777 finds exactly 777 permissions, find /home -perm -644 finds files with at least 644 permissions. Search by type with -type: f (file), d (directory), l (symlink), b (block device), c (character device). Combine criteria with -and (implicit), -or, and -not.
Execute actions on found files with -exec: find /tmp -type f -mtime +30 -exec rm {} \; deletes files older than 30 days. Use -delete for simpler deletion. The {} placeholder represents found files, and \; terminates the command. Use -print (default) to display results. Understanding find is essential for system administration, cleanup tasks, and file management.
140. Explain the df and du commands. How do you check disk space usage and find large files or directories?
Difficulty: MediumType: SubjectiveTopic: Disk Usage
The df (disk free) command displays filesystem disk space usage showing total, used, and available space for mounted filesystems. Use df -h for human-readable output (GB, MB instead of bytes), df -T to show filesystem types, or df /path to check specific filesystem. Df helps monitor disk capacity and identify full filesystems before they cause issues.
The du (disk usage) command estimates file and directory space usage. Use du -h for human-readable sizes, du -s for summary (total only), or du -a to include files (not just directories). du --max-depth=1 shows first-level subdirectories only. Example: du -sh /home/* shows size of each directory in /home, useful for finding what's consuming space.
Find large files with find / -type f -size +1G to list files over 1GB, or combine with du: find /var -type f -exec du -h {} \; | sort -rh | head -20 shows 20 largest files. Use ncdu (NCurses Disk Usage) for interactive browsing of directory sizes with a nice interface, though it's not always installed by default.
For disk usage monitoring, regularly check df output to catch filesystems approaching capacity. Use du to identify large directories, then investigate further. Setting up monitoring alerts when filesystems reach 80-90% capacity prevents production issues. Understanding these tools is crucial for system administration and capacity planning.
141. Explain the difference between a filesystem and a partition. What are common Linux filesystems and their use cases?
Difficulty: HardType: SubjectiveTopic: Filesystem Basics
A partition is a logical division of physical disk space, like dividing a hard drive into separate sections. Each partition can have its own filesystem. Partitions are created with tools like fdisk or parted and appear as /dev/sda1, /dev/sda2, etc. Partitioning allows separating system files from user data, running multiple OS, or organizing data differently.
A filesystem is the method of organizing and storing files on a partition. It defines how data is stored, named, organized, and accessed. The filesystem handles file metadata, directories, permissions, and data block allocation. You create a filesystem on a partition with mkfs command like mkfs.ext4 /dev/sda1.
Common Linux filesystems include ext4 (most common, journaling, good performance, widely supported), XFS (excellent for large files and high-performance servers, used by RHEL 7+), Btrfs (modern with snapshots, compression, and RAID support), and ZFS (advanced features but licensing issues with Linux kernel). Ext4 is the safe default for most uses.
Use cases: ext4 for general purpose systems, XFS for servers with large files or high I/O, Btrfs for systems needing snapshots or advanced features (though less mature than ext4), and tmpfs for /tmp (memory-based, fast but lost on reboot). Understanding filesystems and partitions is fundamental for disk management, system installation, and performance tuning.
142. Explain the chown and chgrp commands. How do you change file ownership and why is it important?
Difficulty: MediumType: SubjectiveTopic: File Ownership
The chown (change owner) command changes file or directory ownership. Syntax: chown user:group filename changes both owner and group, chown user filename changes only owner, and chown :group filename changes only group. Use -R for recursive changes on directories. Example: chown -R www-data:www-data /var/www changes web directory ownership to web server user.
The chgrp command specifically changes group ownership: chgrp groupname filename. While chown can change groups too, chgrp is clearer when only changing groups. Both commands require root privileges to change ownership away from current user, though users can always chown to themselves if they have write permission on the parent directory.
File ownership is crucial for security and access control. Only the owner (or root) can modify file permissions. Web servers need to own website files to serve them, database users need to own database files, and application users need appropriate ownership for their files. Incorrect ownership causes "permission denied" errors and security vulnerabilities.
Common scenarios: after copying files as root, change ownership to the appropriate user; when setting up services, ensure the service account owns its files; after extracting archives, fix ownership for security. Always verify ownership with ls -l showing owner and group in third and fourth columns. Understanding ownership is fundamental for multi-user systems and service configuration.
143. What does the grep command do in Linux?
Difficulty: EasyType: MCQTopic: Grep Regex
- Searches for patterns in files and displays matching lines
- Edits text files
- Compresses files
- Deletes files
Grep (Global Regular Expression Print) searches for patterns in text files and displays lines that match the pattern. It's one of the most powerful and commonly used text processing tools in Linux. Basic syntax is grep 'pattern' filename, which searches filename for lines containing 'pattern' and prints matching lines.
Grep supports regular expressions for complex pattern matching, making it incredibly versatile. Common options include -i for case-insensitive search, -v for inverse match (lines NOT matching), -r for recursive directory search, -n to show line numbers, -c to count matches, and -w for whole word matching.
Grep is essential for log file analysis, code searching, configuration file verification, and data filtering. It's often combined with pipes to filter output from other commands like ps aux | grep nginx to find nginx processes. Understanding grep is fundamental for efficient Linux command-line work and system administration.
Correct Answer: Searches for patterns in files and displays matching lines
144. What is the primary purpose of the sed command?
Difficulty: MediumType: MCQTopic: Text Processing
- Stream editor for filtering and transforming text
- Text file viewer
- File compression tool
- Directory listing
Sed (Stream EDitor) is a powerful stream editor for filtering and transforming text. It reads input line by line, applies specified operations, and outputs the result. Sed is commonly used for search-and-replace operations, text manipulation, and automated editing. Unlike interactive editors, sed processes text programmatically, making it perfect for scripts and automation.
The most common use is substitution: sed 's/old/new/' filename replaces the first occurrence of 'old' with 'new' on each line. Add 'g' flag for global replacement: sed 's/old/new/g' replaces all occurrences. Use -i flag for in-place editing: sed -i 's/old/new/g' filename modifies the file directly.
Sed can delete lines (d command), insert lines (i command), append lines (a command), and perform complex transformations using regular expressions. It's invaluable for configuration file updates, log processing, and batch text transformations. Mastering sed significantly improves productivity in DevOps and system administration roles.
Correct Answer: Stream editor for filtering and transforming text
145. What is awk primarily used for?
Difficulty: MediumType: MCQTopic: Text Processing
- Pattern scanning and text processing language for extracting and manipulating data
- Audio file processing
- Network monitoring
- Process management
Awk is a powerful programming language designed for text processing and data extraction. It treats files as collections of records (lines) divided into fields (columns), making it excellent for processing structured text like CSV files, log files, or command output. Awk processes each line, splits it into fields, and executes specified actions.
Basic awk syntax: awk '{print $1}' filename prints the first field of each line. Fields are separated by whitespace by default, but you can specify custom delimiters with -F option: awk -F':' '{print $1}' /etc/passwd prints usernames. $0 represents the entire line, $1 is the first field, $2 the second, and so on.
Awk supports conditionals, loops, variables, and functions, making it a complete programming language. Common uses include calculating column totals, filtering data based on conditions, reformatting output, and generating reports. Example: awk '$3 > 100' file.txt prints lines where the third field is greater than 100. Understanding awk is valuable for data processing and log analysis in DevOps.
Correct Answer: Pattern scanning and text processing language for extracting and manipulating data
146. What is the difference between cat and less commands?
Difficulty: EasyType: MCQTopic: File Viewing
- cat displays entire file at once, less allows paginated viewing with navigation
- less is faster than cat
- cat can only view small files
- They are exactly the same
Cat (concatenate) displays the entire file content to stdout immediately, useful for small files or when piping to other commands. It shows all content without pausing, so for large files, output scrolls too fast to read. Cat is also used to concatenate multiple files: cat file1 file2 > combined creates a combined file.
Less is a pager that displays file content one screen at a time with navigation controls. Use arrow keys or j/k to scroll, Space for next page, b for previous page, / to search forward, ? to search backward, and q to quit. Less loads files efficiently, even huge files, without loading entire content into memory.
Use cat for small files, piping to other commands, or concatenating files. Use less for large files, log files, or when you need to search and navigate through content. More is similar to less but with fewer features - less is preferred. Understanding when to use each tool improves efficiency when working with files of different sizes.
Correct Answer: cat displays entire file at once, less allows paginated viewing with navigation
147. What does the tail -f command do?
Difficulty: EasyType: MCQTopic: Text Processing
- Displays the last lines of a file and continues to show new lines as they are added
- Deletes the last 10 lines of a file
- Copies the last lines to another file
- Counts lines in a file
Tail -f (follow) displays the last 10 lines of a file by default and continues monitoring the file, displaying new lines as they're appended. This is invaluable for monitoring log files in real-time, seeing application output, or watching file updates without repeatedly running commands. Press Ctrl+C to stop following.
Tail without -f shows the last 10 lines and exits. Use -n option to specify number of lines: tail -n 20 file.log shows last 20 lines. Head does the opposite, showing first lines: head -n 20 file.log shows first 20 lines. Both commands accept input from pipes: ps aux | head -20 shows first 20 processes.
Common usage: tail -f /var/log/syslog for system log monitoring, tail -f /var/log/apache2/error.log for web server debugging. Use tail -F (capital F) to continue following even if the file is rotated (deleted and recreated), important for log files that get rotated. Understanding tail -f is essential for troubleshooting and monitoring production systems.
Correct Answer: Displays the last lines of a file and continues to show new lines as they are added
148. What does the sort -u command do?
Difficulty: MediumType: MCQTopic: Text Processing
- Sorts lines and removes duplicates
- Sorts in uppercase only
- Sorts by username
- Sorts unsorted files only
Sort -u sorts lines in ascending order and removes duplicate lines, combining the functionality of sort and uniq. It's more efficient than piping sort | uniq because it removes duplicates during sorting rather than as a separate step. This is useful for generating unique sorted lists from data with potential duplicates.
The sort command has many useful options: -n for numerical sort (treating content as numbers), -r for reverse order, -k for sorting by specific field, -t for specifying field delimiter, and -h for human-readable numbers (1K, 1M, 1G). Example: sort -t':' -k3 -n /etc/passwd sorts users by UID.
Common usage includes sorting command output like ls -l | sort -k5 -n to sort files by size, or du -h | sort -h to sort disk usage. Use sort for organizing data, finding top/bottom items, or preparing data for uniq command. Understanding sort options enables efficient data manipulation and analysis from command line.
Correct Answer: Sorts lines and removes duplicates
149. What does the cut -d':' -f1 /etc/passwd command do?
Difficulty: MediumType: MCQTopic: Text Processing
- Extracts the first field (username) from each line using colon as delimiter
- Deletes the first line
- Copies the password file
- Cuts the file into parts
Cut extracts specific fields or columns from text files or command output. The -d option specifies the delimiter (colon in this case), and -f specifies which field(s) to extract. Cut -d':' -f1 /etc/passwd extracts usernames because /etc/passwd uses colons to separate fields and usernames are in the first field.
You can extract multiple fields: cut -d':' -f1,6 /etc/passwd extracts usernames and home directories (fields 1 and 6). Use -c to extract by character position: cut -c1-10 file.txt extracts first 10 characters of each line. Cut -f2- extracts from field 2 to the end.
Cut is perfect for parsing structured text like CSV files, log files with consistent formats, or extracting specific columns from command output. Example: ps aux | cut -c1-20 shows first 20 characters of process list. Combine with other tools like grep or sort for powerful data extraction pipelines. Understanding cut enables efficient data extraction from structured text.
Correct Answer: Extracts the first field (username) from each line using colon as delimiter
150. What information does the wc command provide by default?
Difficulty: EasyType: MCQTopic: Text Processing
- Line count, word count, and byte count
- Only word count
- File permissions
- File creation time
Wc (word count) displays the number of lines, words, and bytes in a file by default. The output format is 'lines words bytes filename'. Use wc -l for line count only, wc -w for word count only, wc -c for byte count, or wc -m for character count (different from bytes for multi-byte characters).
Wc is commonly used to count lines in files or command output. Example: wc -l /var/log/syslog counts log entries, or ps aux | wc -l counts running processes. Combining with grep: grep 'error' logfile | wc -l counts error occurrences. This is fundamental for data analysis and monitoring.
In scripts, wc helps validate data processing: checking if output has expected number of lines, verifying file isn't empty (wc -l < file returns 0 for empty), or monitoring file growth. Example: if [ $(wc -l < errors.log) -gt 100 ]; then alert; fi. Understanding wc is essential for data validation and analysis in shell scripts.
Correct Answer: Line count, word count, and byte count
151. Explain how to use grep with regular expressions. Provide examples of common patterns for searching IP addresses, email addresses, and date formats.
Difficulty: HardType: SubjectiveTopic: Grep Regex
Grep supports regular expressions for powerful pattern matching. Use grep -E (extended regex) or egrep for full regex support. Basic patterns include . (any character), * (zero or more), + (one or more), ? (zero or one), ^ (line start), $ (line end), [] (character class), and | (alternation).
To search for IP addresses, use: grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' file.txt matches patterns like 192.168.1.1. For more accuracy: grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}$' ensures entire line is an IP. For email addresses: grep -E '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' finds email patterns.
For dates in YYYY-MM-DD format: grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}' file.txt. For MM/DD/YYYY: grep -E '[0-9]{2}/[0-9]{2}/[0-9]{4}'. Use character classes like [[:digit:]] for portability: grep -E '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}'.
Advanced patterns: grep -E '^(https?://)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' for URLs, grep -E '^[A-Z][a-z]+ [A-Z][a-z]+$' for full names. Use -P for Perl-compatible regex with lookaheads: grep -P '(?=.*[A-Z])(?=.*[0-9])' for lines with uppercase and digits. Mastering regex with grep enables complex log analysis and data extraction.
152. Explain advanced sed operations including multiple substitutions, line deletion, insertion, and using sed with regular expressions.
Difficulty: HardType: SubjectiveTopic: Text Processing
Sed can perform multiple operations with -e flag or semicolons: sed -e 's/old/new/g' -e 's/foo/bar/g' file.txt applies both substitutions. Or use semicolons: sed 's/old/new/g; s/foo/bar/g' file.txt. For complex operations, use sed scripts: sed -f script.sed file.txt where script.sed contains multiple commands.
Line deletion uses d command: sed '5d' deletes line 5, sed '1,10d' deletes lines 1-10, sed '/pattern/d' deletes lines matching pattern. Insertion uses i command: sed '5i\New line text' inserts before line 5. Append uses a command: sed '5a\New line text' appends after line 5. Replace entire line: sed '5c\Replacement line' replaces line 5.
Regex with sed: sed 's/[0-9]\{3\}-[0-9]\{4\}/XXX-XXXX/g' masks phone numbers. Use capturing groups: sed 's/\([0-9]\{4\}\)-\([0-9]\{2\}\)/\2-\1/' swaps year-month to month-year. Address ranges: sed '/start/,/end/s/old/new/g' substitutes only between markers.
Practical examples: sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config changes SSH port, sed '/^$/d' file.txt removes empty lines, sed 's/^[ \t]*//' file.txt removes leading whitespace. Understand sed addresses (line numbers, patterns, ranges) and commands (s, d, i, a, c) for powerful text manipulation in scripts and automation.
153. Explain awk programming features including variables, conditionals, loops, and built-in functions. Provide practical examples.
Difficulty: HardType: SubjectiveTopic: Text Processing
Awk has built-in variables: NR (current record number), NF (number of fields), FS (field separator, default whitespace), RS (record separator, default newline), and OFS (output field separator). Example: awk '{print NR, $0}' file.txt adds line numbers. awk 'NF > 0' file.txt prints non-empty lines.
Conditionals: awk '$3 > 100 {print $1, $3}' file.txt prints first and third fields when third field exceeds 100. Use if-else: awk '{if ($3 > 100) print $1, "high"; else print $1, "low"}' file.txt. Pattern matching: awk '/error/ {count++} END {print count}' file.txt counts error occurrences.
Loops: awk '{for (i=1; i<=NF; i++) sum+=$i} END {print sum}' sums all fields in all lines. While loops: awk '{i=1; while (i<=NF) {print $i; i++}}' prints each field on separate line. Built-in functions include length(), substr(), toupper(), tolower(), split(), gsub(), and mathematical functions like sqrt(), sin(), cos().
Practical examples: awk -F: '{print $1, $3}' /etc/passwd prints usernames and UIDs. awk '{sum+=$1} END {print sum/NR}' calculates average of first column. awk '$3 ~ /^[0-9]+$/ {print $0}' prints lines where third field is numeric. Log analysis: awk '$9==200 {count++} END {print count}' access.log counts HTTP 200 responses. Master awk for complex data processing without external scripts.
154. Explain how to combine multiple text processing commands using pipes. Provide examples of complex data extraction and analysis pipelines.
Difficulty: HardType: SubjectiveTopic: Pipes Redirects
Pipes (|) connect command output to input of next command, enabling powerful data processing pipelines. Each command in pipeline processes data and passes results to next command. Example: cat access.log | grep '200' | awk '{print $1}' | sort | uniq -c | sort -rn extracts IPs with successful requests, counts occurrences, and sorts by frequency.
Breaking down the pipeline: cat reads file, grep filters 200 status codes, awk extracts IP addresses (first field), first sort orders for uniq, uniq -c counts duplicates, final sort -rn orders by count descending. This pattern finds most frequent IPs making successful requests, useful for analyzing web traffic or detecting potential abuse.
Log analysis pipeline: tail -f /var/log/syslog | grep 'ERROR' | awk '{print $5}' | sort | uniq -c monitors errors in real-time, groups by error type, and counts occurrences. CSV processing: cut -d',' -f2,5 data.csv | grep 'active' | sort -t',' -k2 -n extracts specific columns, filters active records, and sorts numerically.
Complex example: ps aux | grep -v grep | awk '$3 > 10 {print $2, $3, $11}' | sort -k2 -rn | head -10 finds top 10 CPU-consuming processes excluding grep. Disk usage: du -h /var | sort -h | tail -20 finds 20 largest directories. Understanding pipelines enables sophisticated data analysis using standard Unix tools without writing custom scripts.
155. Explain the uniq command and why it's typically used with sort. What are the different options for counting and filtering duplicates?
Difficulty: MediumType: SubjectiveTopic: Text Processing
Uniq removes duplicate adjacent lines from input, which is why it's almost always used after sort - sort groups duplicate lines together so uniq can detect them. Without sorting first, uniq only removes duplicates that are consecutive. Example: sort file.txt | uniq removes all duplicate lines after sorting.
Uniq -c counts occurrences of each unique line, prefixing output with count. Example: sort access.log | uniq -c | sort -rn finds most common log entries. Uniq -d shows only duplicate lines (appearing more than once), useful for finding duplicates: sort file.txt | uniq -d. Uniq -u shows only unique lines (appearing exactly once): sort file.txt | uniq -u finds items without duplicates.
Field-based uniqueness: uniq -f N skips first N fields when comparing, useful for structured data. Uniq -w N compares only first N characters. Example: cut -d',' -f1 data.csv | sort | uniq -c counts occurrences of first column values in CSV. Case-insensitive comparison: sort -f file.txt | uniq -i.
Practical examples: ps aux | awk '{print $1}' | sort | uniq -c counts processes per user. sort /var/log/auth.log | uniq finds unique log entries. grep 'ERROR' app.log | sort | uniq -c | sort -rn lists errors by frequency. Understanding sort and uniq together is fundamental for data deduplication and frequency analysis in log files and data processing.
156. Explain the tr command for translating and deleting characters. Provide examples of character conversion, case changes, and character deletion.
Difficulty: MediumType: SubjectiveTopic: Text Processing
Tr (translate) translates or deletes characters from stdin, operating character-by-character. Basic syntax: tr 'set1' 'set2' replaces characters in set1 with corresponding characters in set2. Example: echo 'hello' | tr 'a-z' 'A-Z' converts lowercase to uppercase. Tr 'A-Z' 'a-z' converts uppercase to lowercase.
Delete characters with -d flag: tr -d 'aeiou' removes vowels, tr -d '\n' removes newlines joining lines together. Squeeze repeating characters with -s: tr -s ' ' converts multiple spaces to single space, useful for cleaning up formatted text. Tr -s '\n' removes blank lines (squeezes multiple newlines to one).
Character classes: tr [:lower:] [:upper:] for case conversion (more portable than a-z), tr -d [:digit:] removes all digits, tr -cd [:print:] removes non-printable characters (keeping only printable). Use -c for complement: tr -cd '0-9' keeps only digits, deleting everything else.
Practical examples: cat file.txt | tr -s ' ' | tr ' ' ',' converts space-separated to comma-separated. echo $PATH | tr ':' '\n' displays PATH components on separate lines. tr -d '\r' < dos.txt > unix.txt converts DOS line endings to Unix. Tr is essential for character-level text transformations, file format conversions, and data cleaning in pipelines.
157. Explain the tee command and its use cases. How does it help with logging and debugging pipelines?
Difficulty: MediumType: SubjectiveTopic: Text Processing
Tee reads from stdin and writes to both stdout and one or more files simultaneously, like a T-shaped pipe fitting. This allows capturing pipeline output to a file while still passing it to the next command. Basic usage: command | tee output.txt | next_command saves output to file and continues pipeline.
Use -a flag to append instead of overwrite: command | tee -a log.txt | next_command appends to log file. Multiple files: command | tee file1.txt file2.txt | next_command writes to multiple files. This is valuable for logging, debugging, and creating backups of intermediate pipeline results.
Debugging pipelines: cat data.csv | tee step1.txt | grep 'active' | tee step2.txt | sort saves intermediate results at each step for inspection if pipeline fails. Logging with sudo: echo 'content' | sudo tee /root/file.txt writes to root-owned file (sudo doesn't work with output redirection but does with tee).
Practical examples: make 2>&1 | tee build.log saves build output while displaying it. tail -f /var/log/syslog | tee -a monitor.log | grep 'error' monitors logs, saves everything to file, but only displays errors. script -c 'command' | tee output.txt captures terminal session including timing. Understanding tee improves debugging, logging, and troubleshooting capabilities in complex command pipelines.
158. Explain basic and extended regular expressions in Linux. What are the differences and how do they affect grep, sed, and awk?
Difficulty: HardType: SubjectiveTopic: Grep Regex
Basic Regular Expressions (BRE) require escaping special characters like +, ?, |, {, } to use them as metacharacters. In BRE, grep 'a\+' matches one or more 'a'. Extended Regular Expressions (ERE) treat these as metacharacters by default. Use grep -E or egrep for ERE: grep -E 'a+' matches one or more 'a' without escaping.
Common metacharacters: . (any character), * (zero or more), + (one or more, ERE), ? (zero or one, ERE), ^ (line start), $ (line end), [] (character class), [^] (negated class), () (grouping, ERE or escaped in BRE), | (alternation, ERE or escaped in BRE). Anchors: \b for word boundary (some implementations), \< \> for word start/end.
Grep uses BRE by default, ERE with -E flag. Sed uses BRE by default, ERE with -E or -r flag (GNU sed). Awk uses ERE by default. Examples: grep 'cat\|dog' (BRE) vs grep -E 'cat|dog' (ERE) for alternation. Sed 's/\(word\)/\1s/' (BRE) vs sed -E 's/(word)/\1s/' (ERE) for capture groups.
Character classes: [:alnum:] (alphanumeric), [:alpha:] (alphabetic), [:digit:] (digits), [:space:] (whitespace), [:upper:]/[:lower:] (case). Quantifiers: {n} (exactly n), {n,} (n or more), {n,m} (n to m). Understanding BRE vs ERE prevents regex errors and enables writing portable scripts working across different Unix systems.
159. Explain the paste command and how it differs from cat. Provide examples of merging files side-by-side and with custom delimiters.
Difficulty: MediumType: SubjectiveTopic: Text Processing
Paste merges lines of files side-by-side separated by tabs, unlike cat which concatenates files vertically (one after another). Paste is useful for combining data from multiple files column-wise, like joining parallel arrays or combining related data from separate sources.
Basic usage: paste file1.txt file2.txt places lines from file1 and file2 side-by-side separated by tab. If files have different lengths, paste continues until longest file ends, leaving empty fields for shorter files. Example: paste names.txt ages.txt creates two-column output combining names with ages.
Custom delimiter with -d: paste -d',' file1.txt file2.txt uses comma instead of tab, creating CSV format. Multiple delimiters: paste -d',;' file1.txt file2.txt file3.txt uses comma between first and second file, semicolon between second and third. Use -d'\n' to merge files line-by-line alternating.
Single file operations: paste -s file.txt merges all lines into one line separated by tabs (serial merge). Paste -s -d',' file.txt creates comma-separated single line from multiple lines. Practical example: paste <(cut -d',' -f1 data.csv) <(cut -d',' -f3 data.csv) extracts and combines columns 1 and 3. Understanding paste enables merging datasets and creating structured output from multiple sources.
160. What are best practices for efficient text processing in Linux? Discuss performance considerations and choosing the right tool.
Difficulty: MediumType: SubjectiveTopic: Text Processing
Choose the simplest tool for the task: grep for searching, cut for extracting columns, sed for simple substitutions, awk for complex field processing. Don't use awk when grep suffices, or sed when cut is simpler. Each tool has overhead, so simpler tools are faster for simple tasks. Use built-in shell features like ${var//old/new} for string substitution in variables instead of external commands.
Avoid unnecessary command invocations in loops: instead of while read line; do echo $line | awk '{print $1}'; done use awk directly: awk '{print $1}' file.txt. Process files in single pass when possible rather than multiple passes. Use appropriate tools: awk for structured text, grep for unstructured searching, sed for transformations.
For large files, consider streaming processing with awk, sed, or grep rather than loading entire file into memory. Use -n flag with sed to suppress output except explicitly printed lines. With grep, use -F for fixed strings (faster than regex) when not needing patterns. Consider LC_ALL=C for faster sorting and processing when internationalization isn't needed.
Pipeline efficiency: order commands from most filtering to least - put grep early to reduce data processed by later commands. Example: grep 'pattern' huge.log | awk '{print $1}' | sort | uniq is better than sort huge.log | uniq | grep 'pattern' | awk '{print $1}'. Understanding tool strengths and pipeline ordering creates efficient, maintainable text processing solutions.
161. What is a PID in Linux?
Difficulty: EasyType: MCQTopic: Process Basics
- Process ID - a unique identifier assigned to each running process
- Parent Directory
- Program Installation Directory
- Port Identification
PID (Process ID) is a unique numerical identifier assigned to every running process in Linux. PIDs are assigned sequentially starting from 1, which is always the init or systemd process (the first process started by the kernel). When a process terminates, its PID can be reused for new processes.
Every process has a PID and a PPID (Parent Process ID) indicating which process created it. The ps command shows PIDs, and many system commands accept PIDs as arguments for operations like killing processes, changing priorities, or monitoring specific processes. Understanding PIDs is fundamental for process management.
You can find a process's PID using commands like ps aux | grep processname, pgrep processname, or pidof processname. The special file /proc/PID contains detailed information about each process. PIDs are essential for system administration, troubleshooting, and process control in Linux environments.
Correct Answer: Process ID - a unique identifier assigned to each running process
162. What does the ps aux command display?
Difficulty: EasyType: MCQTopic: Process Monitoring
- All processes for all users with detailed information
- Only current user's processes
- System configuration
- Network connections
The ps aux command displays a comprehensive list of all running processes from all users with detailed information. The 'a' option shows processes for all users, 'u' provides user-oriented format with additional details, and 'x' includes processes not attached to a terminal (daemon processes and background jobs).
The output includes USER (process owner), PID, %CPU (CPU usage), %MEM (memory usage), VSZ (virtual memory size), RSS (resident set size - physical memory), TTY (controlling terminal), STAT (process state), START (start time), TIME (cumulative CPU time), and COMMAND (command that started the process).
Common usage patterns include ps aux | grep processname to find specific processes, ps aux --sort=-%mem to sort by memory usage, or ps aux --sort=-%cpu to sort by CPU usage. Understanding ps aux is essential for monitoring system performance, identifying resource-hungry processes, and troubleshooting issues in production environments.
Correct Answer: All processes for all users with detailed information
163. What is the difference between kill, killall, and pkill commands?
Difficulty: MediumType: MCQTopic: Process Signals
- kill uses PID, killall uses process name, pkill uses pattern matching
- They all do exactly the same thing
- killall is faster than kill
- pkill only works on parent processes
Kill sends signals to processes specified by PID. Basic syntax is kill PID or kill -SIGNAL PID. Without specifying a signal, it sends SIGTERM (15) for graceful termination. Use kill -9 PID (SIGKILL) for forceful termination when processes don't respond to SIGTERM. You must know the exact PID to use kill.
Killall terminates all processes matching a given process name. Syntax: killall processname kills all processes named processname. It's more convenient than kill when multiple instances are running, like killall firefox kills all Firefox processes. Use -u option to kill processes for specific user: killall -u username processname.
Pkill uses pattern matching and additional criteria like user, terminal, or command pattern. Syntax: pkill pattern kills processes matching the pattern. Example: pkill -u username firefox kills Firefox processes for specific user. Pkill is most flexible, allowing combinations like pkill -t pts/0 to kill processes on specific terminal. Understanding these tools helps manage processes efficiently in different scenarios.
Correct Answer: kill uses PID, killall uses process name, pkill uses pattern matching
164. What does the top command do?
Difficulty: MediumType: MCQTopic: Process Monitoring
- Displays real-time system resource usage and running processes dynamically
- Shows only the top 10 files
- Displays network connections
- Shows filesystem hierarchy
Top provides a dynamic, real-time view of running processes and system resource usage. It updates every few seconds showing CPU usage, memory usage, swap usage, running processes sorted by resource consumption. The top section shows system summary including uptime, load average, total/running/sleeping/stopped processes, and CPU/memory statistics.
Interactive commands within top include: k to kill processes, r to renice (change priority), M to sort by memory usage, P to sort by CPU usage, u to filter by user, c to show full command paths, and q to quit. Use top -u username to show processes for specific user, or top -p PID1,PID2 to monitor specific processes.
Top is invaluable for performance monitoring, identifying resource bottlenecks, finding runaway processes, and troubleshooting performance issues. Alternatives include htop (more user-friendly with colors and mouse support) and atop (advanced metrics). Understanding top is essential for system administrators and DevOps engineers managing Linux servers.
Correct Answer: Displays real-time system resource usage and running processes dynamically
165. What does the & symbol do when appended to a command?
Difficulty: MediumType: MCQTopic: Job Control
- Runs the command in the background, returning control to the terminal
- Runs the command as root
- Concatenates commands
- Redirects output to a file
The & symbol at the end of a command runs it in the background, immediately returning control to the terminal so you can continue working. The shell displays a job number and PID when the background job starts. Example: long_running_command & starts the command in the background.
Use jobs command to list background jobs, fg %jobnumber to bring a background job to foreground, and bg %jobnumber to resume a stopped background job. Press Ctrl+Z to suspend a foreground process, then use bg to continue it in the background. This workflow allows managing multiple tasks in a single terminal.
Note that background jobs still send output to the terminal, which can be disruptive. Redirect output to files: command > output.log 2>&1 & sends both stdout and stderr to a file. For persistent background jobs that survive terminal closure, use nohup: nohup command & prevents the job from receiving SIGHUP when the terminal closes.
Understanding background jobs is crucial for running long tasks like backups, data processing, or monitoring scripts without blocking your terminal. Combined with nohup, screen, or tmux, you can manage long-running processes effectively on remote servers.
Correct Answer: Runs the command in the background, returning control to the terminal
166. What is the purpose of the nohup command?
Difficulty: MediumType: MCQTopic: Job Control
- Runs a command immune to hangups, continuing after terminal closes
- Prevents CPU usage
- Disables network connections
- Stops all processes
Nohup (no hangup) runs a command immune to the HUP (hangup) signal, allowing it to continue running even after the terminal session ends or SSH connection drops. When you close a terminal, it normally sends SIGHUP to all child processes, terminating them. Nohup prevents this, making processes persist.
Syntax: nohup command & runs the command in the background, immune to hangups. By default, nohup redirects output to nohup.out in the current directory. Specify custom output: nohup command > custom.log 2>&1 & redirects both stdout and stderr to a custom log file. This is essential for long-running tasks on remote servers.
Nohup is commonly used for processes that must continue running after you log out, like data migrations, backups, batch processing, or monitoring scripts. For more advanced session management with the ability to reattach and view running processes, consider using screen or tmux instead of nohup.
Understanding nohup is crucial for DevOps and system administration, particularly when running maintenance tasks, deployments, or batch jobs on remote servers where network disconnections are possible. It ensures critical processes complete even if your SSH session is interrupted.
Correct Answer: Runs a command immune to hangups, continuing after terminal closes
167. What does the free -h command show?
Difficulty: EasyType: MCQTopic: System Monitoring
- Memory usage in human-readable format (MB, GB)
- Free disk space
- Available ports
- CPU usage
The free command displays memory usage information including total, used, free, shared, buff/cache, and available memory. The -h flag shows values in human-readable format using KB, MB, GB units instead of raw bytes, making it easier to understand at a glance.
Free shows both physical RAM and swap space. The 'available' column indicates memory available for starting new applications without swapping, considering that cached memory can be reclaimed. The buff/cache column shows memory used by kernel buffers and page cache, which can be freed if applications need it.
Common options include free -m (megabytes), free -g (gigabytes), free -s N (continuous updates every N seconds), and free -t (show totals). Example: free -h -s 5 displays human-readable memory stats updating every 5 seconds, useful for monitoring memory during operations.
Understanding free is essential for troubleshooting memory issues, capacity planning, and performance optimization. High swap usage indicates insufficient RAM, while high buff/cache is normal and beneficial. Monitoring memory helps prevent OOM (Out Of Memory) killer from terminating processes unexpectedly.
Correct Answer: Memory usage in human-readable format (MB, GB)
168. What do the three numbers in load average represent?
Difficulty: MediumType: MCQTopic: System Monitoring
- Average number of processes in run queue over 1, 5, and 15 minutes
- CPU usage percentage
- Memory usage levels
- Disk I/O rates
Load average shows the average number of processes in the run queue (ready to run or waiting for resources) over 1, 5, and 15 minute intervals. The uptime command displays these three numbers. For example, 'load average: 2.50, 1.80, 1.20' means 2.50 processes in queue over 1 minute, 1.80 over 5 minutes, and 1.20 over 15 minutes.
Interpret load average relative to CPU cores: on a system with 4 cores, load average of 4.0 means full utilization, below 4.0 means idle capacity, and above 4.0 means processes are waiting. A load of 8.0 on a 4-core system indicates significant queuing. Trending is important: increasing load suggests growing demand, decreasing load suggests stabilizing.
High load average indicates system stress from CPU-intensive processes, I/O wait (disk or network bottlenecks), or too many processes competing for resources. Use top, ps, or iostat to identify the cause. Understanding load average helps assess system health, capacity planning, and troubleshooting performance issues in production environments.
Correct Answer: Average number of processes in run queue over 1, 5, and 15 minutes
169. Explain the different process states in Linux (running, sleeping, stopped, zombie). How do you identify and handle zombie processes?
Difficulty: HardType: SubjectiveTopic: Process Basics
Linux processes exist in several states visible in ps or top output. Running (R) means the process is executing or ready to execute on CPU. Sleeping includes interruptible sleep (S) where process waits for events like I/O and can be interrupted by signals, and uninterruptible sleep (D) where process waits for I/O and cannot be interrupted, often indicating disk or network issues.
Stopped (T) means the process is suspended, typically by Ctrl+Z or a STOP signal. Continue with fg, bg, or CONT signal. Zombie (Z) means the process has finished but hasn't been reaped by its parent - the process table entry remains until the parent calls wait() to collect the exit status. Zombies consume minimal resources (just the process table entry) but indicate parent process issues.
Identify zombies with ps aux | grep Z or ps -eo pid,ppid,state,cmd | grep '^[^ ]* [^ ]* Z'. Zombies can't be killed directly since they're already dead. The solution is to kill the parent process, forcing the zombie to be inherited by init/systemd which will reap it. Find parent: ps -o ppid= -p ZOMBIE_PID, then kill PPID.
Persistent zombies indicate bugs in parent process not properly handling child termination. Well-written programs call wait() or use signal handlers (SIGCHLD) to reap children. In production, monitor for zombie accumulation as it indicates application issues. Understanding process states helps troubleshoot application behavior, hung processes, and resource issues.
170. Explain common Linux signals (SIGTERM, SIGKILL, SIGHUP, SIGINT, SIGSTOP). When should you use each signal?
Difficulty: HardType: SubjectiveTopic: Process Signals
SIGTERM (15) is the default termination signal sent by kill command without arguments. It requests graceful shutdown, allowing the process to clean up resources, close files, save state, and exit cleanly. Well-behaved applications catch SIGTERM, perform cleanup, and exit. Use SIGTERM first when stopping processes to avoid data corruption or resource leaks.
SIGKILL (9) forcefully terminates processes immediately without allowing cleanup. The process cannot catch or ignore SIGKILL - the kernel terminates it immediately. Use SIGKILL only as last resort when SIGTERM fails or for unresponsive processes. Warning: SIGKILL can cause data loss, incomplete transactions, or resource leaks since processes can't clean up.
SIGHUP (1) originally meant hangup (terminal disconnection) but is commonly used to tell daemons to reload configuration without restarting. Many services like nginx, apache, and sshd reload config on SIGHUP: kill -HUP PID or killall -HUP nginx. This allows updating configuration without downtime.
SIGINT (2) is sent by Ctrl+C, requesting interrupt. Like SIGTERM, it allows cleanup but is typically sent interactively. SIGSTOP (19) suspends process execution (can't be caught), while SIGCONT (18) resumes. Use kill -STOP PID to pause process, kill -CONT PID to resume. Understanding signals is essential for proper process management, service restarts, and troubleshooting stuck processes.
171. Explain process priority, nice values, and the renice command. How do you manage process priorities in Linux?
Difficulty: HardType: SubjectiveTopic: Process Priority
Process priority in Linux is controlled by nice values ranging from -20 (highest priority) to 19 (lowest priority). Default nice value is 0. Lower nice values mean higher priority - the process gets more CPU time. The name 'nice' reflects that higher values are 'nicer' to other processes by taking less CPU.
Start processes with specific nice value using nice command: nice -n 10 command starts with nice value 10 (lower priority). Only root can set negative nice values (higher priority): nice -n -5 command. This prevents regular users from prioritizing their processes over system processes.
Change running process priority with renice: renice -n 5 -p PID sets PID's nice value to 5, or renice -n 5 -u username changes all processes for username. In top, press 'r' then enter PID and new nice value. Regular users can only increase nice values (reduce priority) of their processes, while root can set any value.
Use cases: background batch jobs get nice value 10-19 to avoid impacting interactive processes, critical services get nice value -10 to -5 for higher priority, and CPU-intensive tasks like rendering or compilation get higher nice values. Understanding nice values helps optimize resource allocation and prevent low-priority tasks from starving high-priority processes on busy systems.
172. Explain screen and tmux for terminal multiplexing. What are their key features and use cases?
Difficulty: HardType: SubjectiveTopic: Job Control
Screen and tmux are terminal multiplexers allowing multiple terminal sessions in one window, with the crucial ability to detach sessions that continue running and reattach later. This is invaluable for long-running tasks on remote servers - if SSH disconnects, your processes keep running and you can reattach to see their status.
Screen basics: start with screen, detach with Ctrl+A then D, list sessions with screen -ls, reattach with screen -r. Create named sessions: screen -S sessionname. Within screen, Ctrl+A then C creates new window, Ctrl+A then N cycles windows, Ctrl+A then number switches to specific window. Split screen: Ctrl+A then S (horizontal) or Ctrl+A then | (vertical).
Tmux is more modern with similar functionality: start with tmux, detach with Ctrl+B then D, list with tmux ls, attach with tmux attach -t sessionname. Create panes: Ctrl+B then % (vertical split) or Ctrl+B then " (horizontal split). Navigate panes: Ctrl+B then arrow keys. Tmux has better pane management, scripting support, and status bars.
Use cases: running builds or deployments that take hours on remote servers, maintaining IRC or chat sessions, pair programming with shared sessions (screen -x or tmux attach), monitoring logs while working in another window, and ensuring work isn't lost during network interruptions. Essential tools for anyone working with remote Linux servers.
173. Explain the /proc filesystem in Linux. What information does it provide and how do you use it for process and system monitoring?
Difficulty: HardType: SubjectiveTopic: Process Basics
The /proc filesystem is a virtual filesystem providing an interface to kernel data structures, appearing as files and directories but existing only in memory. Each running process has a directory /proc/PID containing detailed process information. /proc also contains system-wide information files for hardware, memory, CPU, and kernel parameters.
Process-specific files in /proc/PID include: cmdline (command with arguments), environ (environment variables), exe (symlink to executable), cwd (current working directory), fd/ (open file descriptors), status (detailed status including memory usage, UIDs, GIDs), limits (resource limits), and maps (memory mappings). Example: cat /proc/1234/cmdline shows the command for PID 1234.
System-wide files include: /proc/cpuinfo (CPU details), /proc/meminfo (memory details more complete than free), /proc/version (kernel version), /proc/uptime (system uptime), /proc/loadavg (load average), /proc/mounts (mounted filesystems), /proc/net/ (network statistics), and /proc/sys/ (tunable kernel parameters).
Practical usage: cat /proc/meminfo | grep MemAvailable checks available memory, cat /proc/cpuinfo | grep processor | wc -l counts CPU cores, cat /proc/PID/status | grep VmRSS shows process memory usage. Write to /proc/sys to tune kernel parameters: echo 1 > /proc/sys/net/ipv4/ip_forward enables IP forwarding. Understanding /proc enables low-level system inspection and tuning without external tools.
174. Compare different system monitoring tools: top, htop, vmstat, iostat, and sar. When should you use each tool?
Difficulty: MediumType: SubjectiveTopic: Process Monitoring
Top provides real-time process monitoring and system resource overview, showing CPU usage, memory usage, and processes sorted by resource consumption. It's the most common tool for quick system checks and identifying resource hogs. Use top for interactive process monitoring, finding high CPU/memory processes, and getting overall system health snapshot.
Htop is an enhanced top with color coding, mouse support, horizontal/vertical scrolling, tree view of processes, and easier process management. It's more user-friendly but not always installed by default. Use htop when available for better visualization and easier process navigation, especially in complex process hierarchies.
Vmstat (virtual memory statistics) reports process, memory, paging, block I/O, traps, and CPU activity. Run vmstat 5 for updates every 5 seconds. Focus on columns: r (processes waiting for CPU), b (blocked processes), swpd (swap usage), si/so (swap in/out), bi/bo (blocks in/out), us/sy/id/wa (CPU time breakdown). Use vmstat for identifying memory pressure, swap activity, and CPU bottlenecks over time.
Iostat (I/O statistics) reports CPU and I/O statistics for devices and partitions. Run iostat -x 5 for extended statistics every 5 seconds. Key metrics: %util (device utilization), await (average wait time), svctm (service time). Use iostat for diagnosing disk I/O bottlenecks, identifying slow disks, and understanding I/O patterns. Sar (System Activity Reporter) collects and reports system activity over time, storing historical data. Use sar for analyzing performance trends, post-mortem analysis, and capacity planning. Each tool provides different perspective on system performance.
175. Explain job control in Linux shells. How do you manage foreground and background jobs, suspend and resume processes?
Difficulty: MediumType: SubjectiveTopic: Job Control
Job control allows managing multiple processes from a single shell, switching between foreground and background execution. Start commands in background with &: command & returns control immediately. The shell assigns job number [1], [2], etc., and shows PID. Use jobs command to list jobs with status (Running, Stopped, Done) and job numbers.
Suspend foreground process with Ctrl+Z, which sends SIGTSTP (terminal stop). The process stops and control returns to shell, showing '[1]+ Stopped command'. Resume in foreground with fg %jobnumber or just fg for most recent job. Resume in background with bg %jobnumber, making the stopped job continue in background.
Job specifiers: %1 (job number 1), %% or %+ (current job), %- (previous job), %?str (job whose command contains str), %command (job whose command starts with command). Examples: fg %2 brings job 2 to foreground, kill %1 kills job 1. Without %, shell interprets numbers as PIDs not job numbers.
Practical workflow: start long compilation in foreground, press Ctrl+Z to suspend, run bg to continue in background, start another command in foreground. Use jobs to check status, fg %1 to bring back first job when ready to check it. This enables parallel work without multiple terminals. Understanding job control improves productivity on remote servers with limited terminal access.
176. How do you troubleshoot high CPU usage or memory issues? Describe the steps and commands you would use to identify and resolve the problem.
Difficulty: HardType: SubjectiveTopic: Process Monitoring
Start with top or htop to identify processes consuming high CPU or memory. Press M in top to sort by memory, P for CPU. Note the PID and %CPU/%MEM values. For CPU issues, look for processes with consistently high CPU usage. For memory, check both RSS (resident memory) and VIRT (virtual memory) in ps aux output.
Investigate specific process: ps aux | grep PID shows details, cat /proc/PID/status shows comprehensive status including memory breakdown, cat /proc/PID/cmdline shows full command. Check open files with lsof -p PID to see if process has too many open files. Use pmap PID to view detailed memory mapping and identify memory hogs.
For CPU issues: strace -p PID shows system calls, identifying what the process is doing. If looping, look for repeated calls. pstack PID (or gstack) shows call stack for debugging where process is stuck. Check if CPU spike is legitimate (processing) or a bug (infinite loop). Review application logs for errors or warnings.
For memory issues: check if it's a memory leak by monitoring memory growth over time: watch -n 10 'ps aux | grep PID'. Review application logs for OutOfMemoryError or similar. Check swap usage with free -h and vmstat - high swap indicates insufficient RAM. If memory leak suspected, restart the application and monitor, potentially after enabling memory profiling.
Resolution steps: restart misbehaving process if safe, investigate application logs for root cause, apply limits with ulimit or systemd if process consumes excessive resources, optimize application if performance issue is legitimate, or add resources (CPU/RAM) if system is underpowered. Document findings and solutions for future reference.
177. What are best practices for monitoring processes in production environments? Discuss proactive monitoring and alerting strategies.
Difficulty: MediumType: SubjectiveTopic: Process Monitoring
Implement automated monitoring using tools like Prometheus, Nagios, or Datadog that continuously collect metrics (CPU, memory, disk, network) and alert when thresholds are exceeded. Set up alerts for critical metrics: CPU usage > 80%, memory usage > 90%, disk usage > 85%, load average > number of cores, and process count anomalies.
Monitor process-specific metrics: check that critical services are running with pidof or systemctl status, monitor process restart counts indicating instability, track resource consumption trends for capacity planning, and set up health checks for application endpoints. Use cron jobs or systemd timers for periodic checks if dedicated monitoring tools aren't available.
Log aggregation and analysis: centralize logs with ELK stack, Splunk, or CloudWatch, monitor error rates and patterns, set up alerts for critical log patterns like OutOfMemoryError or connection timeouts, and retain historical data for trend analysis and incident investigation.
Proactive strategies: establish baseline metrics for normal operation to detect anomalies, implement resource limits with ulimit or cgroup to prevent runaway processes from affecting the system, use process supervisors like systemd or supervisord to automatically restart failed processes, and regularly review and tune monitoring thresholds based on actual incidents to reduce false positives.
Document runbooks for common issues: high CPU resolution steps, memory leak troubleshooting, process stuck in D state handling, and zombie process cleanup. Automate remediation where safe: automatic service restart on failure, clearing temp directories, or releasing file handles. Balance automation with safety to prevent cascading failures from automated actions.
178. Which command is used to add a new user in Linux?
Difficulty: EasyType: MCQTopic: User Management
- useradd
- adduser
- newuser
- createuser
The useradd command creates a new user account with specified parameters. Basic syntax: useradd username creates a user with default settings. Common options include -m to create home directory, -s to specify shell (e.g., /bin/bash), -G to add to supplementary groups, -c for comment (full name), and -d to specify custom home directory.
Example: useradd -m -s /bin/bash -G sudo,docker -c 'John Doe' johndoe creates user johndoe with home directory, bash shell, adds to sudo and docker groups, and sets full name. After creation, set password with passwd johndoe. The user account is stored in /etc/passwd with encrypted password in /etc/shadow.
Note that adduser (on Debian/Ubuntu) is a more user-friendly wrapper script around useradd that interactively prompts for information and sets up the home directory automatically. Useradd is the lower-level command available on all Linux distributions. Understanding useradd is essential for user management in production servers and automation scripts.
Correct Answer: useradd
179. What is the purpose of the sudo command?
Difficulty: EasyType: MCQTopic: Privilege Escalation
- Allows authorized users to run commands as root or another user
- Switches to root user permanently
- Shuts down the system
- Suspends processes
Sudo (superuser do) allows authorized users to execute commands with elevated privileges, typically as root, without logging in as root. This provides better security through auditing (all sudo commands are logged), accountability (tracking who ran what), and least privilege principle (users only get root access when needed, not permanent root access).
Basic usage: sudo command runs command as root after password verification. Sudo -u username command runs as different user. Sudo -i opens root shell. Configuration is in /etc/sudoers file, edited with visudo command (never edit directly). Grant sudo access by adding users to sudo group (Debian/Ubuntu) or wheel group (RHEL/CentOS).
Sudoers file allows fine-grained control: which users can run which commands, on which hosts, as which users, with or without password. Example entry: username ALL=(ALL:ALL) ALL gives username full sudo access. NOPASSWD option allows running sudo without password for specific commands. Understanding sudo is crucial for secure multi-user system administration.
Correct Answer: Allows authorized users to run commands as root or another user
180. What information is stored in /etc/passwd file?
Difficulty: MediumType: MCQTopic: User Management
- User account information including username, UID, GID, home directory, and shell
- Encrypted user passwords
- System configuration
- Network settings
The /etc/passwd file contains user account information in colon-separated fields: username:x:UID:GID:comment:home_directory:shell. Example: john:x:1001:1001:John Doe:/home/john:/bin/bash. The 'x' in password field indicates password is in /etc/shadow (shadowed passwords for security).
UID (User ID) is numerical identifier for the user, with 0 for root, 1-999 for system accounts, and 1000+ for regular users (varies by distribution). GID (Group ID) is the primary group. Comment field typically contains full name. Home directory is the user's personal space, and shell is the login shell (e.g., /bin/bash, /bin/sh, /sbin/nologin for accounts that shouldn't login).
The /etc/passwd file is world-readable because many programs need to look up username-to-UID mappings. However, actual passwords are stored in /etc/shadow which is only readable by root. Understanding /etc/passwd structure is essential for user management, troubleshooting login issues, and scripting user administration tasks.
Correct Answer: User account information including username, UID, GID, home directory, and shell
181. Which file contains group information in Linux?
Difficulty: EasyType: MCQTopic: Group Management
- /etc/group
- /etc/groups
- /etc/passwd
- /etc/shadow
The /etc/group file contains group information with format: groupname:x:GID:member_list. Example: developers:x:1005:john,jane,bob defines a group 'developers' with GID 1005 and three members. The 'x' in password field indicates group password (rarely used, stored in /etc/gshadow if set).
Each user has a primary group (specified in /etc/passwd) and can belong to multiple supplementary groups (listed in /etc/group). Primary group is the default group for files created by the user. Supplementary groups provide additional permissions. Check user's groups with groups username or id username commands.
Group management commands include groupadd to create groups, groupdel to delete groups, groupmod to modify groups, and usermod -aG to add users to groups. Example: groupadd developers creates developers group, usermod -aG developers john adds john to developers group without removing from other groups (-a for append, without it replaces all groups).
Understanding groups is crucial for managing file access permissions, especially in multi-user environments or for controlling access to resources like Docker (docker group), sudo access (sudo/wheel group), or development tools. Groups enable flexible, maintainable access control without managing individual user permissions.
Correct Answer: /etc/group
182. What is the difference between su and su - commands?
Difficulty: MediumType: MCQTopic: Privilege Escalation
- su - starts a login shell with target user's environment, su keeps current environment
- su is faster than su -
- su - requires password, su doesn't
- They are exactly the same
Su (substitute user) switches to another user account, defaulting to root if no username specified. Plain su command switches user but maintains the current environment (PATH, variables, working directory). This can cause issues if the new user's environment differs significantly from the original user's environment.
Su - (or su -l) starts a login shell for the target user, fully switching to their environment including PATH, HOME, SHELL, USER variables, and changing to their home directory. This simulates a fresh login as that user. Su - is generally preferred because it provides a clean, expected environment for the target user.
Examples: su switches to root keeping current environment, su - root switches to root with root's full environment, su - john switches to john with john's environment. Su -c 'command' user runs a single command as user without starting interactive shell. Sudo is generally preferred over su for administrative tasks due to better auditing and the principle of least privilege.
Understanding the difference prevents environment-related issues when switching users, especially when running commands that depend on specific environment variables or paths. For automation and scripts, explicitly specify environment requirements rather than relying on inherited environment.
Correct Answer: su - starts a login shell with target user's environment, su keeps current environment
183. What permissions does chmod 644 set?
Difficulty: MediumType: MCQTopic: File Permissions
- Owner: read+write, Group: read, Others: read
- Owner: read only, Group: write, Others: execute
- Everyone: read+write+execute
- Owner: execute only
Octal notation uses three digits where each represents permissions for owner, group, and others. Each digit is sum of: read (4), write (2), execute (1). So 644 breaks down as: 6 (4+2 = rw-) for owner, 4 (r--) for group, 4 (r--) for others. This is standard for regular data files.
Common permission patterns: 644 (rw-r--r--) for regular files - owner can modify, others can read; 755 (rwxr-xr-x) for executables and directories - owner has full access, others can read and execute; 600 (rw-------) for sensitive files like private keys - only owner can access; 777 (rwxrwxrwx) for fully open files (insecure, rarely appropriate).
Directory permissions: read (4) allows listing contents, write (2) allows creating/deleting files, execute (1) allows entering directory and accessing files. Without execute on directory, you can't access files even if files have read permission. Understanding this is crucial: directories typically need 755 or 775 permissions to be useful.
Set permissions with chmod: chmod 644 file.txt (numeric), chmod u+x file.sh (symbolic - add execute for owner), chmod go-w file.txt (remove write for group and others). Use -R for recursive: chmod -R 755 directory. Proper permissions are critical for security, preventing unauthorized access while allowing necessary operations.
Correct Answer: Owner: read+write, Group: read, Others: read
184. What does the sticky bit do on a directory?
Difficulty: HardType: MCQTopic: File Permissions
- Allows only file owners to delete their files in the directory
- Makes the directory read-only
- Prevents anyone from entering the directory
- Automatically backs up files
The sticky bit on directories restricts file deletion - only the file owner, directory owner, or root can delete or rename files, even if the directory is world-writable. This prevents users from deleting others' files in shared directories. The classic use case is /tmp directory where all users can create files but shouldn't delete others' files.
Set sticky bit with chmod +t directory or chmod 1777 directory (1 in leading position indicates sticky bit). In ls -l output, sticky bit shows as 't' in others execute position (drwxrwxrwt). If directory isn't executable for others, it shows as 'T' (drwxrwxrwT).
Without sticky bit, anyone with write permission on a directory can delete any file in it regardless of file ownership. This is dangerous for shared directories. The sticky bit ensures that in collaborative spaces like /tmp or /var/tmp, users can only manage their own files, preventing accidental or malicious deletion of others' files.
Practical example: mkdir /shared && chmod 1777 /shared creates a shared directory where everyone can create files, but only owners can delete their files. Understanding sticky bit is essential for managing shared directories securely in multi-user environments.
Correct Answer: Allows only file owners to delete their files in the directory
185. What are Access Control Lists (ACLs) in Linux?
Difficulty: HardType: MCQTopic: File Permissions
- Extended permissions allowing fine-grained access control beyond standard owner/group/other
- A type of firewall rule
- Network access controls
- Application configuration lists
ACLs (Access Control Lists) extend the traditional Linux permission model by allowing specific permissions for individual users or groups beyond the single owner, group, and others. This enables fine-grained control when the basic permission model is insufficient, like granting read access to multiple specific users without creating groups.
Set ACL with setfacl: setfacl -m u:john:rw file.txt grants user john read+write access, setfacl -m g:developers:r file.txt grants developers group read access. View ACLs with getfacl file.txt. Remove with setfacl -x u:john file.txt. The -R flag applies ACLs recursively to directories.
ACL mask defines maximum permissions that can be granted to named users and groups. Default ACLs on directories set permissions for newly created files. Example: setfacl -d -m u:john:rw directory sets default ACL so files created in directory automatically give john read+write access.
Files with ACLs show '+' in ls -l output: -rw-rw-r--+ indicates ACLs are set. Not all filesystems support ACLs - ext4, XFS, and Btrfs do, but filesystem must be mounted with ACL support. Understanding ACLs is important for complex access control scenarios in enterprise environments where basic permissions are insufficient.
Correct Answer: Extended permissions allowing fine-grained access control beyond standard owner/group/other
186. Explain the complete process of creating, modifying, and deleting user accounts. Include commands, files involved, and best practices.
Difficulty: MediumType: SubjectiveTopic: User Management
Create user with useradd: useradd -m -s /bin/bash -G sudo,docker -c 'Full Name' username creates user with home directory (-m), bash shell (-s), adds to groups (-G), and sets comment (-c). Set password immediately with passwd username for security. Verify creation with id username showing UID, GID, and groups.
Modify users with usermod: usermod -aG newgroup username adds to supplementary group (append, doesn't remove existing), usermod -s /bin/zsh username changes shell, usermod -L username locks account (prevents login), usermod -U username unlocks. Change primary group with usermod -g groupname username. Rename user with usermod -l newname oldname, but manually rename home directory with mv /home/oldname /home/newname.
Delete users with userdel: userdel username removes user but leaves home directory and files, userdel -r username removes user and home directory (use caution - data loss). Check for running processes with ps -u username before deletion. Find files owned by deleted users with find / -uid UID -ls, then reassign ownership or delete as appropriate.
Best practices: use consistent UID ranges (1000+ for regular users), enforce strong passwords with PAM configuration, lock accounts rather than deleting for users who leave (preserves file ownership), audit user access regularly, document account purposes especially for service accounts, set account expiration dates with chage for temporary accounts, and maintain user provisioning/deprovisioning procedures.
Security considerations: disable root SSH login (PermitRootLogin no in sshd_config), require key-based authentication, set password policies (minimum length, complexity, expiration), monitor for unauthorized accounts in /etc/passwd, and regularly review sudo access. Automate user management with configuration management tools like Ansible or Puppet for consistency across multiple systems.
187. How do you troubleshoot permission denied errors? Describe the systematic approach to identifying and fixing permission issues.
Difficulty: HardType: SubjectiveTopic: File Permissions
Start by identifying what operation failed and what user performed it. Check file permissions with ls -l filename, showing owner, group, and permissions. Check user's identity and groups with id username or whoami and groups. Match user's groups against file's group to understand access level. Check if special permissions (setuid, setgid, sticky bit) are involved with ls -l.
Verify directory permissions in the path. To access a file, you need execute permission on all parent directories. Example: accessing /home/user/data/file.txt requires execute on /, /home, /home/user, and /home/user/data, plus read on file.txt. Use namei -l /path/to/file to show permissions for entire path, identifying where access fails.
Check ACLs with getfacl filename if '+' appears in ls -l output. ACLs might grant or deny access beyond standard permissions. Check SELinux context with ls -Z filename if SELinux is enabled - wrong context causes permission denied even with correct file permissions. Verify with getenforce showing Enforcing/Permissive/Disabled. Check audit logs at /var/log/audit/audit.log for SELinux denials.
Common fixes: chmod to adjust file permissions, chown to change ownership, chgrp to change group, usermod -aG to add user to required group (requires logout/login), setfacl to add specific user/group access, chcon or restorecon to fix SELinux contexts. For directories, ensure execute permission. For shared access, consider creating shared group, setting group ownership, and using 2770 permissions (rwxrws--- with setgid).
Preventive measures: use umask to set default permissions for new files (e.g., umask 0022 for 644 files, 755 directories), document permission schemes, establish ownership standards for shared directories, use group-based access control over ACLs when possible for simplicity, and test permission changes before applying to production. Understanding permission inheritance and defaults prevents future issues.
188. Explain the /etc/sudoers file structure and how to configure granular sudo access. Include examples of different sudo configurations.
Difficulty: HardType: SubjectiveTopic: Sudoers Config
The /etc/sudoers file controls sudo access and must be edited with visudo command (never edit directly - visudo validates syntax preventing lockout). Basic syntax: user host=(runas_user:runas_group) commands. Example: john ALL=(ALL:ALL) ALL gives john full sudo access on all hosts, running any command as any user/group.
User specifications: root ALL=(ALL:ALL) ALL (root has full access), %sudo ALL=(ALL:ALL) ALL (group specification with % prefix - all sudo group members have full access), john ALL=(ALL) NOPASSWD: ALL (john doesn't need password for sudo), jane ALL=/usr/bin/systemctl,/usr/bin/service (jane can only run specific commands with sudo).
Command aliases simplify management: Cmnd_Alias SERVICES = /usr/bin/systemctl, /usr/bin/service then john ALL=(root) SERVICES allows john to run service management commands. User aliases: User_Alias ADMINS = john, jane, bob then ADMINS ALL=(ALL) ALL gives multiple users access. Host aliases for multi-host environments: Host_Alias WEBSERVERS = web1, web2.
Advanced configurations: john ALL=(apache) NOPASSWD: /usr/bin/systemctl restart httpd allows john to restart apache as apache user without password, useful for deployment scripts. Restrict to specific hosts: john WEBSERVERS=(ALL) ALL only on webservers. Deny commands: john ALL=(ALL) ALL, !/usr/bin/rm -rf / (whitelist with blacklist exceptions, though blacklisting is generally ineffective).
Best practices: use visudo always (syntax checking), prefer groups over individual users (easier management), use NOPASSWD sparingly (security risk), be specific with command paths (prevents PATH manipulation), validate command arguments where possible, include sudoers.d directory (includedir /etc/sudoers.d) for modular configuration, test sudo rules thoroughly, and document why each rule exists. Regular audits prevent permission creep.
189. Explain password management in Linux including /etc/shadow, password policies, and the chage command. How do you enforce password complexity and expiration?
Difficulty: HardType: SubjectiveTopic: Password Management
The /etc/shadow file stores encrypted passwords and password aging information, readable only by root. Format: username:encrypted_password:last_change:min:max:warn:inactive:expire:reserved. Last_change is days since epoch of last password change, min is minimum days between changes, max is maximum days before required change, warn is warning days before expiration, inactive is days after expiration before account locks, expire is absolute expiration date.
Manage password aging with chage: chage -l username displays aging information, chage -M 90 username sets maximum 90 days between password changes, chage -m 7 username sets minimum 7 days between changes (prevents immediate password change back), chage -W 14 username warns 14 days before expiration, chage -E 2024-12-31 username sets account expiration date, chage -I 30 username locks account 30 days after password expires.
Enforce password complexity with PAM (Pluggable Authentication Modules) configuration in /etc/pam.d/common-password (Debian/Ubuntu) or /etc/pam.d/system-auth (RHEL/CentOS). Install libpam-pwquality package. Configure with pam_pwquality.so: minlen=12 (minimum length), dcredit=-1 (require digit), ucredit=-1 (require uppercase), ocredit=-1 (require special char), lcredit=-1 (require lowercase), difok=3 (minimum character changes from old password), maxrepeat=2 (max repeated characters).
Password history prevents reusing recent passwords: configure pam_unix.so remember=10 to remember last 10 passwords. Failed login attempts: pam_faillock.so locks accounts after N failed attempts within time window, mitigating brute force. Example: deny=5 unlock_time=900 locks after 5 failures for 15 minutes.
Best practices: enforce minimum complexity (12+ characters, mixed case, numbers, symbols), regular password changes (60-90 days max age), prevent password reuse (remember last 10+), account lockout after failed attempts, user education on password security, consider key-based authentication over passwords for SSH, use password managers for complex passwords, and regular password audits with tools like John the Ripper (authorized testing only).
190. What are service accounts and how should they be managed? Explain best practices for creating and securing service accounts.
Difficulty: MediumType: SubjectiveTopic: Privilege Escalation
Service accounts are special user accounts for running services, applications, or automated processes rather than for human login. They typically have /sbin/nologin or /bin/false as shell preventing interactive login, and UIDs in system range (often 1-999). Examples: www-data for web servers, mysql for MySQL database, nobody for unprivileged operations.
Create service accounts with useradd -r -s /sbin/nologin -c 'Service Description' servicename. The -r flag creates system account with UID in system range. Assign minimal necessary permissions following least privilege principle - service accounts should only access files/directories needed for their function. Use dedicated groups for service account permissions rather than giving broad access.
Security best practices: disable password login (service accounts shouldn't have passwords), use SSH keys or other authentication mechanisms if remote access needed, restrict sudo access (service accounts rarely need sudo), set proper file ownership (service should own its files), use SELinux or AppArmor to confine service processes, regularly audit service account permissions, document each service account's purpose, and remove unused service accounts.
For containerized environments, avoid root in containers - use USER directive in Dockerfile to run as non-root service account. For Kubernetes, use ServiceAccount resources with RBAC for permissions. For cloud platforms, use IAM roles instead of long-lived credentials. Never share service accounts across different services - each service should have dedicated account for auditing and isolation.
Monitoring: track service account activity in logs, alert on unexpected access patterns (service accounts have predictable behavior), audit file access, and regularly review permissions. Use configuration management tools (Ansible, Puppet) to ensure consistent service account setup across systems. Document which human administrator is responsible for each service account.
191. Explain umask in Linux. How does it work and how do you calculate default permissions for new files and directories?
Difficulty: HardType: SubjectiveTopic: File Permissions
Umask (user file creation mask) defines default permissions for newly created files and directories by specifying which permission bits to remove from the default permissions. Default permissions before umask are 666 (rw-rw-rw-) for files and 777 (rwxrwxrwx) for directories. Umask subtracts permissions from these defaults.
Calculation: umask 0022 (common default) removes write permission for group and others. For files: 666 - 022 = 644 (rw-r--r--). For directories: 777 - 022 = 755 (rwxr-xr-x). Note that umask 0002 would give 664 for files and 775 for directories, allowing group write access. More restrictive umask 0077 gives 600 files and 700 directories (owner-only access).
Set umask temporarily with umask 0022 command (affects current shell session). Set permanently in ~/.bashrc, ~/.profile, or /etc/profile for system-wide defaults. View current umask with umask command showing octal value, or umask -S showing symbolic format (u=rwx,g=rx,o=rx). Different umask for different users by setting in individual profiles.
Common umask values: 0022 (files 644, dirs 755) - standard for most users, allows others to read but not modify; 0002 (files 664, dirs 775) - collaborative environments where group members share write access; 0077 (files 600, dirs 700) - restrictive, only owner has access, used for sensitive data; 0000 (files 666, dirs 777) - fully permissive, rarely appropriate.
Security considerations: more restrictive umask is more secure but less convenient for collaboration. Choose based on environment: single-user workstations can use 0022, shared servers might need 0002 for group collaboration, security-sensitive systems should use 0077. Remember umask affects default permissions - can always change permissions after creation with chmod. Understanding umask prevents permission issues with newly created files.
192. Explain setuid and setgid special permissions. Provide examples of when they're necessary and security implications.
Difficulty: HardType: SubjectiveTopic: Privilege Escalation
Setuid (Set User ID) on executable files causes the file to execute with owner's privileges instead of the executor's. When setuid bit is set on file owned by root, any user running it executes with root privileges. Indicated by 's' in owner execute position (rwsr-xr-x). Set with chmod u+s file or chmod 4755 file (4 in leading digit).
Classic example: /usr/bin/passwd has setuid bit and is owned by root. Regular users need to modify /etc/shadow (root-only file) to change their password. Setuid allows passwd to run as root, modify shadow file, but only accepts user's own password change. Other examples: sudo, su, ping (needs raw sockets requiring root), mount (some implementations).
Setgid (Set Group ID) on executables causes execution with file's group privileges. Indicated by 's' in group execute position (rwxr-sr-x). Set with chmod g+s file or chmod 2755 file. On directories, setgid causes new files to inherit directory's group instead of creator's primary group, useful for shared directories where all files should be group-owned.
Setgid directory example: mkdir /shared/project && chgrp developers /shared/project && chmod 2775 /shared/project creates shared directory where all files inherit developers group ownership, allowing team collaboration. Without setgid, files would have creator's primary group, potentially breaking access for team members.
Security implications: setuid/setgid are major security risks if misused - they're common attack vectors. Audit setuid files regularly: find / -perm -4000 -type f 2>/dev/null lists all setuid files. Review necessity, ensure secure coding (no shell command injection, buffer overflows, path manipulation). Remove setuid from unnecessary files. Avoid creating custom setuid programs unless absolutely necessary and thoroughly security-reviewed. Use capabilities instead of setuid where possible (more granular privileges). SELinux can restrict setuid operations. Understanding these permissions is critical for security hardening.
193. What are best practices for managing a multi-user Linux system? Discuss user isolation, resource limits, and security hardening.
Difficulty: HardType: SubjectiveTopic: Privilege Escalation
User isolation: each user should have separate home directory (mode 700) preventing other users from accessing their files. Use private groups (one group per user) as primary group. Avoid shared accounts - each person should have individual account for accountability. Separate service accounts from user accounts. Use PAM to restrict which users can login, which services they can use, and from where (IP restrictions).
Resource limits with ulimit or /etc/security/limits.conf prevent users from consuming excessive resources. Set limits on: max processes (nproc), max open files (nofile), max file size (fsize), max CPU time (cpu), max memory (as, rss). Example: username hard nproc 100 limits user to 100 processes. Use cgroups for more sophisticated resource management including CPU shares, memory limits, and I/O priorities.
Password policies: enforce strong passwords with pam_pwquality, set maximum password age with chage, implement account lockout after failed attempts with pam_faillock, require password on sudo unless specific exceptions, disable root login over SSH, and use key-based authentication where possible. Regular password audits detect weak passwords before attackers do.
Access control: principle of least privilege - grant minimum necessary permissions. Use groups for permission management rather than ACLs when possible. Regularly audit user accounts removing inactive accounts (lastlog shows last login). Monitor suspicious activity with log analysis (failed login attempts, sudo usage, file access). Set up proper file ownership on shared directories with setgid and appropriate umask.
Monitoring and auditing: enable audit logging with auditd, monitor logs for suspicious patterns (excessive failed logins, privilege escalation attempts, unusual file access), set up alerts for critical events, track sudo usage, and regularly review user list in /etc/passwd. Use centralized logging for multi-system environments. Implement file integrity monitoring (AIDE, Tripwire) to detect unauthorized changes to system files.
194. Which command displays network interface configuration in Linux?
Difficulty: EasyType: MCQTopic: Networking Basics
- ifconfig or ip addr
- netstat
- ping
- route
The ifconfig command (interface configuration) displays network interface information including IP addresses, MAC addresses, netmasks, and interface status. However, ifconfig is deprecated in favor of the ip command from the iproute2 package. Use ip addr or ip a to show interface configuration with more detailed information.
Both commands show interface names (eth0, ens33, wlan0), IP addresses (IPv4 and IPv6), MAC addresses, MTU (Maximum Transmission Unit), and interface state (UP/DOWN). Ip addr provides additional information like scope (global, link, host) and is more powerful with consistent syntax across different operations.
Example output shows lo (loopback) interface at 127.0.0.1, and physical interfaces with assigned IP addresses. Understanding interface configuration is fundamental for network troubleshooting, configuring static IPs, and diagnosing connectivity issues. Modern systems prefer ip command, but ifconfig is still widely used and understood.
Correct Answer: ifconfig or ip addr
195. What does the ping command do?
Difficulty: EasyType: MCQTopic: Network Diagnostics
- Tests network connectivity by sending ICMP echo requests
- Displays port status
- Shows routing tables
- Configures IP addresses
Ping sends ICMP (Internet Control Message Protocol) echo request packets to a target host and waits for echo reply packets. It measures round-trip time and packet loss, helping diagnose network connectivity and latency issues. Basic usage: ping hostname or ping IP_address sends continuous pings until interrupted with Ctrl+C.
Common options include -c count to send specific number of packets (ping -c 4 google.com sends 4 packets then stops), -i interval to set time between packets, -W timeout for response timeout, and -s size to set packet size. Output shows bytes received, sequence number, TTL (Time To Live), and time in milliseconds.
Ping results help diagnose issues: 100% packet loss indicates no connectivity, high latency suggests network congestion or distant host, variable times indicate unstable connection, and 'Destination Host Unreachable' suggests routing problems. Some hosts block ICMP for security, causing ping to fail even when host is accessible via other protocols. Understanding ping is essential for basic network troubleshooting.
Correct Answer: Tests network connectivity by sending ICMP echo requests
196. What is SSH used for in Linux?
Difficulty: EasyType: MCQTopic: SSH Command
- Secure remote login and command execution over encrypted connection
- File compression
- Process management
- Disk partitioning
SSH (Secure Shell) provides secure encrypted remote access to Linux systems over networks. It replaces insecure protocols like telnet and rlogin, encrypting all traffic including authentication credentials. Basic usage: ssh username@hostname connects to remote host, prompting for password or using SSH keys for authentication.
SSH enables remote command execution: ssh user@host 'command' runs command on remote host without interactive login. Port forwarding: ssh -L local_port:remote_host:remote_port creates secure tunnel for services. SCP and rsync use SSH for secure file transfer. SSH is fundamental for remote system administration, especially in cloud and DevOps environments.
Key-based authentication is more secure than passwords: generate keys with ssh-keygen, copy public key to remote host with ssh-copy-id user@host, then login without password. Configure SSH in /etc/ssh/sshd_config including port, allowed users, root login permission, and key-only authentication. Understanding SSH is critical for managing remote Linux servers securely.
Correct Answer: Secure remote login and command execution over encrypted connection
197. What does netstat -tuln show?
Difficulty: MediumType: MCQTopic: Network Diagnostics
- TCP and UDP listening ports with numeric addresses
- Network speed
- DNS configuration
- Wireless networks
Netstat displays network connections, routing tables, interface statistics, and more. The flags -tuln show: -t (TCP connections), -u (UDP connections), -l (listening ports only), -n (numeric output without hostname resolution, faster). This combination shows all services listening for network connections, useful for security audits and troubleshooting.
Output shows protocol (tcp/udp), local address:port (0.0.0.0:80 means listening on all interfaces), foreign address (connections from), and state (LISTEN, ESTABLISHED, TIME_WAIT). Example: 0.0.0.0:22 in LISTEN state indicates SSH server listening on all interfaces port 22.
Netstat is being replaced by ss (socket statistics) command which is faster and provides more detailed information: ss -tuln gives same output but performs better on busy systems. Both commands are essential for identifying which services are running, detecting unauthorized services, verifying firewall rules, and troubleshooting network services that won't start due to port conflicts.
Correct Answer: TCP and UDP listening ports with numeric addresses
198. Which command updates package lists on Debian/Ubuntu systems?
Difficulty: EasyType: MCQTopic: Package Management
- apt update or apt-get update
- apt install
- apt upgrade
- apt search
Apt update (or apt-get update) refreshes the local package index from configured repositories, downloading information about available packages and their versions. This doesn't install or upgrade packages - it just updates the package lists so apt knows what's available. Run this before installing packages to ensure you get the latest versions.
The apt command is newer, more user-friendly interface to apt-get with colored output and progress bars. Commands: apt update (refresh package lists), apt upgrade (upgrade installed packages), apt install package (install new package), apt remove package (remove package), apt search keyword (search packages), apt show package (show package details).
Common workflow: sudo apt update (refresh lists), sudo apt upgrade (upgrade all packages), sudo apt install nginx (install nginx). Use apt autoremove to remove unused dependencies. Configuration files in /etc/apt/sources.list and /etc/apt/sources.list.d/ define repositories. Understanding apt is essential for software management on Debian-based systems including Ubuntu, the most popular Linux distribution.
Correct Answer: apt update or apt-get update
199. What package manager does RHEL/CentOS use?
Difficulty: EasyType: MCQTopic: Package Management
- yum or dnf
- apt
- pacman
- zypper
YUM (Yellowdog Updater Modified) is the traditional package manager for Red Hat-based distributions including RHEL, CentOS, and Fedora. DNF (Dandified YUM) is the modern replacement, offering better performance and dependency resolution. Both use RPM packages (.rpm files) and have similar command syntax.
Common yum/dnf commands: yum update (update all packages), yum install package (install package), yum remove package (remove package), yum search keyword (search packages), yum info package (show details), yum list installed (list installed packages). Use sudo for administrative operations. DNF is default in Fedora and newer RHEL/CentOS versions.
Repository configuration in /etc/yum.repos.d/ defines package sources. YUM/DNF automatically handles dependencies, downloading and installing required packages. Use yum clean all to clear cache. Understanding yum/dnf is crucial for managing RHEL/CentOS systems commonly used in enterprise environments and is important for DevOps professionals working with diverse Linux distributions.
Correct Answer: yum or dnf
200. What does systemctl enable do?
Difficulty: MediumType: MCQTopic: Service Management
- Configures service to start automatically at boot
- Starts a service immediately
- Stops a service
- Shows service logs
Systemctl enable creates symbolic links for a service unit file, configuring it to start automatically at system boot. This doesn't start the service immediately - it only sets it to auto-start on future boots. Use systemctl start to start immediately, or systemctl enable --now to both enable and start in one command.
Systemctl is the command-line interface to systemd, the init system used by most modern Linux distributions. Common commands: systemctl start service (start service), systemctl stop service (stop service), systemctl restart service (restart service), systemctl reload service (reload config without restart), systemctl status service (show status and recent logs), systemctl disable service (disable auto-start).
Systemctl list-units --type=service shows all services. Systemctl daemon-reload reloads systemd configuration after editing unit files. Systemctl is-enabled service checks if service is set to auto-start. Understanding systemctl is fundamental for managing services in modern Linux systems, controlling web servers, databases, monitoring agents, and custom applications.
Correct Answer: Configures service to start automatically at boot
201. What is curl primarily used for?
Difficulty: MediumType: MCQTopic: Network Diagnostics
- Transferring data from or to servers using various protocols including HTTP
- File compression
- Text editing
- Process monitoring
Curl (Client URL) is a command-line tool for transferring data using various protocols including HTTP, HTTPS, FTP, SFTP, and more. It's commonly used for API testing, downloading files, checking HTTP responses, and debugging web services. Basic usage: curl URL displays response from URL.
Common options: -o filename saves output to file, -O downloads file with original name, -I shows only headers, -X METHOD specifies HTTP method (GET, POST, PUT, DELETE), -H 'Header: value' adds custom headers, -d 'data' sends POST data, -u user:pass for authentication, -k ignores SSL certificate validation. Example: curl -X POST -H 'Content-Type: application/json' -d '{"key":"value"}' URL posts JSON data.
Curl is essential for DevOps automation, testing REST APIs, health checks in monitoring scripts, downloading files in scripts, and debugging HTTP issues. It shows detailed information about requests and responses, supports authentication, follows redirects with -L flag, and handles cookies. Understanding curl is crucial for working with web services and APIs from command line.
Correct Answer: Transferring data from or to servers using various protocols including HTTP
202. Describe a systematic approach to troubleshooting network connectivity issues. Include commands and diagnostic steps.
Difficulty: HardType: SubjectiveTopic: Network Diagnostics
Start with basic connectivity: ping 127.0.0.1 tests loopback interface ensuring TCP/IP stack works. Ping default gateway (ip route | grep default shows gateway) tests local network connectivity. Ping external IP like 8.8.8.8 (Google DNS) tests internet connectivity without DNS. If this works but domain names don't, the issue is DNS.
Check interface configuration: ip addr shows IP addresses and interface status (UP/DOWN), ip link shows physical layer status. Verify correct IP address, subnet mask, and interface is UP. Check route table with ip route or route -n ensuring default gateway exists. Incorrect IP configuration or missing gateway prevents communication beyond local network.
DNS troubleshooting: cat /etc/resolv.conf shows configured DNS servers. Test DNS with nslookup domain or dig domain. If resolution fails, try different DNS server: nslookup domain 8.8.8.8. Check /etc/hosts for local hostname overrides. NetworkManager or systemd-resolved might manage DNS configuration - check their status.
Port and service testing: telnet host port or nc -zv host port tests specific port connectivity. Check if service is listening with netstat -tuln or ss -tuln. Verify firewall rules with iptables -L -n or firewall-cmd --list-all. Check if remote firewall blocks connection. Use tcpdump or wireshark for packet capture: tcpdump -i eth0 port 80 captures HTTP traffic for detailed analysis.
Common issues and solutions: no IP address (DHCP problem - check dhclient or NetworkManager), wrong subnet (verify netmask), no default gateway (check routing), DNS failure (check resolv.conf and DNS server), firewall blocking (check iptables/firewalld), cable unplugged (check ip link for interface state), service not listening (check netstat and service status). Document findings and solutions for future reference.
203. Explain SSH key-based authentication and security best practices for SSH configuration. How do you set up and secure SSH access?
Difficulty: HardType: SubjectiveTopic: SSH Security
Generate SSH key pair with ssh-keygen -t rsa -b 4096 -C 'comment' creating private key (~/.ssh/id_rsa) and public key (~/.ssh/id_rsa.pub). Never share private key. Use ed25519 keys for better security with smaller key size: ssh-keygen -t ed25519. Protect private key with passphrase for additional security layer.
Copy public key to remote server with ssh-copy-id user@host or manually append public key to ~/.ssh/authorized_keys on remote server with correct permissions (700 for .ssh directory, 600 for authorized_keys file). Test key authentication: ssh user@host should login without password. If prompted for password, check permissions and sshd_config settings.
Secure SSH configuration in /etc/ssh/sshd_config: disable root login (PermitRootLogin no), disable password authentication (PasswordAuthentication no) after setting up keys, change default port (Port 2222) for security through obscurity, allow specific users (AllowUsers user1 user2), use Protocol 2 only, set LoginGraceTime 30 to prevent connection hanging attacks, limit authentication attempts (MaxAuthTries 3).
Advanced security: use fail2ban to block brute force attempts by banning IPs with multiple failed logins, configure two-factor authentication with Google Authenticator PAM module, use SSH certificates instead of keys for large deployments, implement jump hosts/bastion servers for accessing internal networks, restrict SSH access by IP with firewall rules or TCPWrappers (/etc/hosts.allow, /etc/hosts.deny).
Monitoring and auditing: monitor /var/log/auth.log for failed login attempts and suspicious activity, set up alerts for successful root logins or logins from unexpected IPs, regularly audit authorized_keys files for unauthorized entries, rotate SSH keys periodically, and review SSH configuration with tools like ssh-audit. Apply updates promptly to patch security vulnerabilities. Understanding SSH security is critical for protecting server access.
204. Explain firewall configuration in Linux using iptables and firewalld. How do you allow or block network traffic?
Difficulty: HardType: SubjectiveTopic: Firewall Tools
Iptables is the traditional Linux firewall managing packet filtering rules. Rules organized in chains (INPUT for incoming, OUTPUT for outgoing, FORWARD for routed packets) within tables (filter, nat, mangle). View rules with iptables -L -n -v. Rules processed sequentially - first matching rule applies, so order matters.
Basic iptables rules: iptables -A INPUT -p tcp --dport 22 -j ACCEPT allows SSH, iptables -A INPUT -p tcp --dport 80 -j ACCEPT allows HTTP, iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT allows traffic from specific subnet, iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT allows established connections. Set default policy: iptables -P INPUT DROP drops all not explicitly allowed.
Persist iptables rules with iptables-save > /etc/iptables/rules.v4 and restore with iptables-restore < /etc/iptables/rules.v4. Install iptables-persistent package on Debian/Ubuntu for automatic persistence. Delete rule: iptables -D INPUT rule_number. Insert rule at specific position: iptables -I INPUT 1 rule inserts at top.
Firewalld (default on RHEL/CentOS 7+) provides dynamic firewall management with zones concept. List zones: firewall-cmd --get-zones. Default zone: firewall-cmd --get-default-zone. Add service: firewall-cmd --add-service=http --permanent (permanent flag persists across reboots). Add port: firewall-cmd --add-port=8080/tcp --permanent. Reload: firewall-cmd --reload applies changes.
Firewalld zones: public (default for public interfaces, limited access), internal (trusted internal networks), dmz (DMZ with limited external access), trusted (all traffic allowed). Rich rules provide advanced control: firewall-cmd --add-rich-rule='rule family=ipv4 source address=1.2.3.4 reject' --permanent. Understanding firewall management is essential for securing Linux servers against unauthorized access.
205. Explain DNS configuration in Linux including /etc/hosts, /etc/resolv.conf, and DNS troubleshooting commands.
Difficulty: MediumType: SubjectiveTopic: DNS Config
The /etc/hosts file provides static hostname-to-IP mappings checked before DNS queries. Format: IP_address hostname [aliases]. Example: 127.0.0.1 localhost, 192.168.1.10 server.local server. Changes take effect immediately. Use hosts file for local development, overriding DNS for specific hosts, or improving resolution speed for frequently accessed hosts.
The /etc/resolv.conf file configures DNS servers for system-wide name resolution. Format: nameserver IP lists DNS servers (queries in order listed), search domain sets search domains for short hostnames, domain sets local domain. Example: nameserver 8.8.8.8, nameserver 8.8.4.4 uses Google DNS. Modern systems often have resolv.conf managed by systemd-resolved or NetworkManager - check for symlinks.
Systemd-resolved manages DNS in modern systems. Configuration in /etc/systemd/resolved.conf. Check status: systemd-resolve --status or resolvectl status. Set DNS servers: resolvectl dns interface 8.8.8.8. Flush cache: resolvectl flush-caches. Resolution order: /etc/hosts → systemd-resolved cache → configured DNS servers → /etc/nsswitch.conf defines this order.
DNS troubleshooting tools: nslookup domain shows DNS query result and server used. Dig (domain information groper) provides detailed DNS query information: dig domain shows A record, dig domain MX shows mail servers, dig @8.8.8.8 domain queries specific DNS server, dig +trace domain shows full DNS resolution path from root servers. Host command: host domain simpler output than dig.
Common DNS issues: wrong DNS server (check resolv.conf), DNS server not responding (test with dig @server), caching issues (flush cache), local hosts file overriding DNS (check /etc/hosts), NetworkManager overwriting resolv.conf (make immutable with chattr +i or configure NetworkManager). Understanding DNS configuration is crucial for network connectivity and troubleshooting name resolution issues.
206. Explain advanced package management including repository configuration, package dependencies, and resolving package conflicts.
Difficulty: HardType: SubjectiveTopic: Package Management
Repository configuration for Debian/Ubuntu in /etc/apt/sources.list and /etc/apt/sources.list.d/*.list. Format: deb http://repo.url/ubuntu focal main restricted adds repository for Ubuntu 20.04 (focal). Components: main (officially supported), restricted (proprietary drivers), universe (community maintained), multiverse (restricted by copyright). Add PPA (Personal Package Archive): add-apt-repository ppa:user/repo adds third-party repository.
RHEL/CentOS repository configuration in /etc/yum.repos.d/*.repo. Format: [repo-id] name=Repository Name, baseurl=http://repo.url, enabled=1, gpgcheck=1, gpgkey=http://repo.url/RPM-GPG-KEY. Add EPEL (Extra Packages for Enterprise Linux): yum install epel-release adds additional packages not in official repos. Import GPG keys: rpm --import keyfile verifies package authenticity.
Dependency management: apt/yum automatically resolve dependencies installing required packages. Check dependencies: apt-cache depends package or yum deplist package. Reverse dependencies: apt-cache rdepends package shows packages depending on this one. Broken dependencies: apt --fix-broken install or yum check resolves issues. Hold packages from upgrade: apt-mark hold package or yum versionlock add package.
Package conflicts occur when packages provide same files or have incompatible dependencies. Resolve by: identifying conflicting packages (dpkg -S filename shows which package owns file), removing one conflicting package, using alternatives system (update-alternatives --config program selects default), or building from source if packaged versions conflict. Force installation with dpkg --force-overwrite or rpm --force (use cautiously - can break system).
Best practices: keep systems updated (security patches), enable automatic security updates, test updates on non-production first, use stable repositories for production (avoid testing/unstable), document custom repositories and packages, backup before major upgrades, monitor package changelogs for breaking changes, and clean package cache periodically (apt clean, yum clean all). Understanding package management prevents dependency hell and maintains stable systems.
207. Compare different methods for transferring files between Linux systems: scp, rsync, and sftp. When should you use each?
Difficulty: MediumType: SubjectiveTopic: File Transfer
SCP (Secure Copy) uses SSH protocol for encrypted file transfers. Basic usage: scp source user@host:destination copies to remote, scp user@host:source destination copies from remote. Copy directories: scp -r directory/ user@host:path. Preserve timestamps and permissions: scp -p. Simple and secure but copies entire files even if destination has similar file - no delta transfer optimization.
Rsync is more efficient, only transferring changed portions of files (delta transfer). Basic usage: rsync -avz source/ user@host:destination. Flags: -a (archive mode preserving permissions, timestamps, symlinks), -v (verbose), -z (compression), -P (progress and partial transfers). Rsync over SSH: rsync -avz -e ssh. Exclude files: rsync --exclude='*.tmp'. Dry run: rsync -n tests without changes.
Rsync advantages: resume interrupted transfers, only transfer changed data (efficient for large files or slow connections), delete files in destination not in source (--delete), bandwidth limiting (--bw-limit), preserve hard links, ACLs, and extended attributes. Use rsync for backups, syncing large directories, or when source and destination have similar content. Rsync is ideal for incremental backups and mirroring.
SFTP (SSH File Transfer Protocol) provides interactive file transfer over SSH with commands similar to FTP. Connect: sftp user@host. Commands: ls (remote list), lls (local list), cd (remote change dir), lcd (local change dir), put file (upload), get file (download), mkdir, rm. Batch mode: sftp -b batchfile user@host processes commands from file. Good for interactive transfers or when GUI-like interface needed.
Choose SCP for simple one-time transfers of small files, rsync for efficient transfers of large directories or when files might change (backups, syncing), and SFTP for interactive browsing and transferring. All use SSH for security. For very large files, consider rsync with compression (--compress-level=9) and progress monitoring. Understanding these tools enables efficient secure file transfers in DevOps workflows.
208. Explain systemd service management including creating custom service units, service dependencies, and troubleshooting service failures.
Difficulty: HardType: SubjectiveTopic: Service Management
Systemd service units defined in /etc/systemd/system/ (custom) or /lib/systemd/system/ (packaged). Unit file format has [Unit], [Service], and [Install] sections. Example: [Unit] Description=My Service, After=network.target ensures service starts after network. [Service] Type=simple, User=appuser, ExecStart=/path/to/binary, Restart=on-failure. [Install] WantedBy=multi-user.target enables with systemctl enable.
Service types: simple (default, main process specified by ExecStart), forking (service forks background process), oneshot (process expected to exit, good for scripts), notify (service sends notification when ready), idle (delays execution until other jobs finish). Choose type based on application behavior. ExecStartPre and ExecStartPost run commands before/after main process.
Dependencies and ordering: Wants= suggests dependencies (service starts even if dependency fails), Requires= enforces dependencies (service fails if dependency fails), After=/Before= controls ordering without enforcing dependencies. Example: After=postgresql.service Requires=postgresql.service ensures database starts first and is required. Conflicts= prevents services from running simultaneously.
Troubleshooting: systemctl status service shows current state and recent logs. Journalctl -u service shows full logs, journalctl -u service -f follows logs live, journalctl -u service --since "1 hour ago" filters by time. Check service file syntax: systemd-analyze verify service.service. View dependencies: systemctl list-dependencies service. Test configuration: systemctl daemon-reload reloads after editing units.
Common issues: service fails immediately (check ExecStart path and permissions), service times out starting (increase TimeoutStartSec or fix slow startup), service restarts repeatedly (check Restart= setting and logs for crash cause), service doesn't start at boot (check WantedBy= and systemctl enable status), environment variables not set (use Environment= or EnvironmentFile=). Create minimal test service to isolate issues. Understanding systemd is crucial for managing services in modern Linux environments.
209. Explain advanced network diagnostic tools including traceroute, mtr, tcpdump, and netcat. Provide use cases for each.
Difficulty: HardType: SubjectiveTopic: Network Diagnostics
Traceroute maps the network path to a destination showing each hop (router) along the way. Basic usage: traceroute hostname. Output shows hop number, hostname/IP, and three round-trip times. High latency at specific hop indicates bottleneck. Asterisks (*) indicate no response (router filtering ICMP). Use traceroute to identify where network delays or failures occur, troubleshoot routing issues, or understand network topology.
MTR (My Traceroute) combines ping and traceroute functionality, continuously monitoring network path and providing statistics. Usage: mtr hostname displays real-time updating view. Shows loss percentage, sent/received packet counts, and latency statistics (best, average, worst, standard deviation) for each hop. More useful than traceroute for identifying intermittent issues or patterns. Use mtr to diagnose packet loss locations, identify unstable network paths, or monitor connection quality over time.
Tcpdump captures and analyzes network packets at low level. Basic usage: tcpdump -i interface captures on specific interface, tcpdump port 80 captures HTTP traffic, tcpdump host 1.2.3.4 captures traffic to/from specific host, tcpdump -w file.pcap saves to file for later analysis. Filters: tcpdump 'tcp and port 443' captures HTTPS. Advanced: tcpdump -A shows packet contents in ASCII. Use tcpdump to debug protocol-level issues, verify firewall rules, analyze network problems, or capture traffic for security analysis.
Netcat (nc) is networking Swiss Army knife for reading/writing network connections. Uses: nc -l -p port listens on port (server mode), nc host port connects to host:port (client mode). Test port connectivity: nc -zv host port scans port. Transfer files: nc -l -p 1234 > file (receiver), nc host 1234 < file (sender). Debug services by manually sending protocol commands: nc smtp_server 25 to interact with mail server. Create simple TCP/UDP clients and servers for testing.
Combining tools: use ping for basic connectivity, traceroute to identify path issues, mtr for ongoing monitoring and statistics, tcpdump for detailed protocol analysis, and netcat for testing specific ports or protocols. Each tool provides different perspective on network behavior. Understanding these tools enables diagnosing complex network issues efficiently.
210. How do you ensure package security in Linux? Discuss package verification, security updates, and vulnerability scanning.
Difficulty: MediumType: SubjectiveTopic: Package Management
Package verification uses GPG signatures to ensure packages haven't been tampered with and come from trusted sources. APT checks signatures automatically if repository provides Release.gpg file. Import repository keys: apt-key add keyfile (legacy) or place in /etc/apt/trusted.gpg.d/. For YUM/DNF, gpgcheck=1 in repo configuration enables verification, keys imported with rpm --import. Verify individual packages: rpm -K package.rpm checks signature.
Security updates are critical for patching vulnerabilities. Enable automatic security updates: install unattended-upgrades on Debian/Ubuntu, configure /etc/apt/apt.conf.d/50unattended-upgrades to only install security updates. For RHEL/CentOS, yum-cron or dnf-automatic handle automatic updates. Configure notification on updates. Test updates in staging before production, but don't delay security patches excessively.
Monitor security advisories: subscribe to distribution security mailing lists (ubuntu-security-announce, centos-announce), check vendor security pages, or use automated tools. Apt-get changelog package shows recent changes including security fixes. Yum updateinfo list security shows available security updates. USN (Ubuntu Security Notices) and RHSA (Red Hat Security Advisories) provide detailed vulnerability information.
Vulnerability scanning: use tools like Lynis (system auditing), OpenSCAP (security compliance), or commercial scanners like Nessus. Check installed packages for known vulnerabilities: apt-cache policy shows installed versions, compare against CVE databases. Debian Security Tracker and Red Hat CVE database track vulnerabilities. Debsecan on Debian identifies packages with security issues.
Best practices: minimize installed packages (smaller attack surface), keep systems updated (automate security patches), verify package sources (only use trusted repositories), audit installed packages regularly (remove unused), use configuration management to maintain consistent secure state, monitor security advisories proactively, and scan for vulnerabilities periodically. Consider container security scanning for containerized applications. Understanding package security prevents compromised packages from affecting systems.
211. What is the purpose of the shebang (#!) line at the beginning of a shell script?
Difficulty: EasyType: MCQTopic: Shell Scripting
- Specifies which interpreter should execute the script
- Comments out the first line
- Makes the script executable
- Imports libraries
The shebang (#!) on the first line tells the system which interpreter to use for executing the script. Common shebangs: #!/bin/bash for Bash scripts, #!/bin/sh for POSIX shell scripts, #!/usr/bin/env python3 for Python (uses env to find Python in PATH). The kernel reads this line when you execute the script directly (./script.sh), passing the script to the specified interpreter.
Without shebang, the script runs with the current shell (often bash), which might not be what you want. Use #!/bin/bash when using bash-specific features like arrays, [[ ]], and extended syntax. Use #!/bin/sh for portable scripts that should run with any POSIX-compliant shell. The env approach (#!/usr/bin/env bash) is more portable across systems with different installation paths.
Note: shebang must be the very first line with no preceding whitespace or blank lines. Make script executable with chmod +x script.sh. Then run with ./script.sh. Understanding shebang is fundamental for writing scripts that execute correctly and portably across different environments.
Correct Answer: Specifies which interpreter should execute the script
212. How do you assign and access a variable in bash?
Difficulty: EasyType: MCQTopic: Shell Variables
- Assign with VAR=value, access with $VAR
- Assign with $VAR=value, access with VAR
- Assign with VAR:value, access with &VAR
- Assign with set VAR value, access with get VAR
Variables in bash are assigned without spaces around equals sign: VAR=value or VAR='value with spaces'. Access variable value with dollar sign: $VAR or ${VAR} (braces for clarity). No spaces allowed around = during assignment - VAR = value causes error trying to execute VAR as command.
Quote variables to handle spaces and special characters: GREETING='Hello World'. Access: echo $GREETING outputs Hello World. Use double quotes to expand variables: echo "$GREETING, $USER" expands both variables. Single quotes prevent expansion: echo '$GREETING' outputs literal $GREETING.
Braces clarify variable names especially with concatenation: ${VAR}suffix prevents ambiguity. Unset variables with unset VAR. Read-only variables: readonly VAR=value or declare -r VAR=value prevents modification. Check if variable set: [ -z "$VAR" ] tests if empty/unset. Understanding variable syntax is fundamental to shell scripting.
Correct Answer: Assign with VAR=value, access with $VAR
213. What does $@ represent in a shell script?
Difficulty: MediumType: MCQTopic: Script Arguments
- All positional parameters as separate words
- The script name
- The number of arguments
- The last argument
Special variables for arguments: $0 (script name), $1-$9 (first 9 arguments, ${10} for 10th onward), $# (number of arguments), $@ (all arguments as separate words), $* (all arguments as single word), $? (exit status of last command). Use "$@" (quoted) to preserve individual arguments correctly, especially with spaces.
Example: script.sh arg1 'arg 2' arg3 gives $1=arg1, $2=arg 2, $3=arg3, $#=3. Loop through arguments: for arg in "$@"; do echo "$arg"; done. Shift removes first argument moving others down: shift makes $2 become $1. Use shift to process arguments in loops.
Difference between $@ and $*: "$@" expands to "$1" "$2" "$3" (separate words), "$*" expands to "$1 $2 $3" (single word with IFS separator). Always quote "$@" to handle arguments with spaces correctly. Check argument count: if [ $# -eq 0 ]; then echo 'No arguments'; exit 1; fi. Understanding argument handling is essential for creating flexible, reusable scripts.
Correct Answer: All positional parameters as separate words
214. What does 2>&1 do in shell scripting?
Difficulty: MediumType: MCQTopic: Pipes Redirects
- Redirects stderr (2) to wherever stdout (1) is going
- Redirects stdout to stderr
- Creates two output files
- Duplicates the output twice
Standard streams: stdin (0), stdout (1), stderr (2). Redirection operators: > redirects stdout to file (overwrites), >> appends stdout, 2> redirects stderr, 2>&1 redirects stderr to stdout's current destination. Example: command > output.txt 2>&1 sends both stdout and stderr to output.txt. Order matters: redirect stdout first, then stderr to stdout.
Common patterns: command > /dev/null 2>&1 discards all output (both stdout and stderr to null device), command 2> error.log logs only errors, command > output.log 2>&1 captures both in single file. Use &> or >& as shorthand for > file 2>&1 in bash (redirects both to file).
Input redirection: < file reads stdin from file, << EOF creates here document (multi-line input until EOF), <<< 'string' provides string as stdin. Pipe | connects stdout of one command to stdin of next: command1 | command2. Understanding redirection is crucial for handling script output, logging, error handling, and creating pipelines.
Correct Answer: Redirects stderr (2) to wherever stdout (1) is going
215. What does an exit status of 0 indicate?
Difficulty: EasyType: MCQTopic: Exit Status
- Success - command completed without errors
- Failure
- Warning
- Command still running
Exit status (return code) indicates whether command succeeded (0) or failed (non-zero). Access with $? immediately after command: command; echo $? shows exit status. By convention: 0 = success, 1-255 = various failure modes. Some commands use specific codes: grep returns 1 if no matches, 2 for errors.
Set exit status in scripts with exit N where N is 0-255. Exit 0 indicates success, exit 1 indicates general error. Not using exit allows script to return status of last command. Check status in conditionals: if command; then echo 'Success'; else echo 'Failed'; fi. The if statement checks whether command returns 0 (true) or non-zero (false).
Set -e makes script exit on any command failure (non-zero status), useful for safer scripts. Set -o pipefail makes pipelines return failure if any command fails (default returns status of last command). Understanding exit status enables proper error handling and conditional execution in scripts.
Correct Answer: Success - command completed without errors
216. What does the pipe (|) operator do?
Difficulty: EasyType: MCQTopic: Pipes Redirects
- Connects stdout of one command to stdin of the next command
- Redirects output to a file
- Creates logical OR condition
- Comments out code
The pipe operator | connects the standard output of one command to the standard input of the next, enabling command chaining and data processing pipelines. Example: cat file.txt | grep 'pattern' | sort | uniq reads file, filters matching lines, sorts them, and removes duplicates. Each command processes data from previous and passes results to next.
Pipes work with any commands accepting stdin: ls -l | grep '.txt' lists only .txt files, ps aux | grep nginx finds nginx processes, cat access.log | awk '{print $1}' | sort | uniq -c counts requests per IP. Stderr isn't piped by default - use 2>&1 before pipe to include stderr: command 2>&1 | grep error.
Pipelines execute all commands concurrently, not sequentially. Exit status of pipeline is status of last command unless set -o pipefail enabled. Pipes enable powerful data processing without temporary files. Understanding pipes is fundamental to shell scripting and command-line efficiency, enabling complex operations through simple command composition.
Correct Answer: Connects stdout of one command to stdin of the next command
217. What is the difference between $(command) and `command`?
Difficulty: MediumType: MCQTopic: Command Substitution
- $(command) is newer, more readable, and nestable; both execute command and return output
- `command` is faster
- $(command) only works in bash
- They are completely different operations
Command substitution executes command and replaces it with its output. Both $(command) and `command` work but $(command) is preferred modern syntax. Example: DATE=$(date +%Y-%m-%d) assigns current date to variable, FILES=$(ls *.txt) assigns file list. Use quotes to preserve newlines: "$(command)" keeps line breaks.
Advantages of $(command): easily nestable $(command1 $(command2)), more readable especially with complex expressions, works consistently across shells. Backticks `command` are legacy syntax, harder to nest (requires escaping: \`command\`), less readable in complex expressions. Both execute in subshell, so variable assignments inside don't affect parent shell.
Common uses: TODAY=$(date +%Y-%m-%d), COUNT=$(wc -l < file), IP=$(hostname -I | awk '{print $1}'). Store command output: OUTPUT=$(command 2>&1) captures both stdout and stderr. Inline usage: echo "There are $(ls | wc -l) files". Understanding command substitution enables dynamic scripts that adapt to system state and command output.
Correct Answer: $(command) is newer, more readable, and nestable; both execute command and return output
218. What is the difference between single quotes, double quotes, and no quotes in bash?
Difficulty: HardType: MCQTopic: Shell Scripting
- Single quotes: literal (no expansion), double quotes: expand variables, no quotes: word splitting and globbing
- All quotes work the same way
- Single quotes are faster
- Double quotes prevent all expansion
Single quotes preserve everything literally - no variable expansion, no command substitution, no escape sequences: echo '$USER \n' outputs literal $USER \n. Only way to include single quote inside single quotes is to end quote, escape quote, start new quote: 'don\'t' or use "don't" with double quotes.
Double quotes allow variable expansion, command substitution, and some escape sequences: echo "$USER \n" expands $USER and interprets \n. Preserve spaces: VAR="value with spaces" keeps spaces. Dollar, backticks, backslash, and double quote can be escaped inside double quotes: echo "\$USER" outputs literal $USER.
No quotes enable word splitting (spaces separate words) and pathname expansion (globbing): FILES=*.txt expands to matching filenames, echo $FILES splits on spaces. Dangerous with variables containing spaces: rm $FILE might delete multiple files if FILE="file 1.txt file 2.txt". Always quote variables: rm "$FILE" treats as single argument.
Best practices: use single quotes for literal strings, double quotes for strings with variables or command substitution, always quote variables in expansions unless you specifically want word splitting. Understanding quoting prevents bugs from unexpected word splitting and ensures proper handling of filenames with spaces and special characters.
Correct Answer: Single quotes: literal (no expansion), double quotes: expand variables, no quotes: word splitting and globbing
219. Explain the basic structure of a well-written shell script including shebang, comments, error handling, and style conventions.
Difficulty: MediumType: SubjectiveTopic: Shell Scripting
Start with proper shebang: #!/bin/bash or #!/bin/sh depending on required features. Add script description comments at top explaining purpose, usage, author, and date. Example:
```bash
#!/bin/bash
# Script: backup.sh
# Purpose: Backup specified directory
# Usage: ./backup.sh <source_dir> <dest_dir>
# Author: John Doe
# Date: 2024-01-15
```
Enable strict mode for safer scripts: set -e (exit on error), set -u (exit on undefined variable), set -o pipefail (pipeline returns failure if any command fails). Together: set -euo pipefail catches more errors. Add IFS=$'\n\t' to prevent word splitting issues. Use 'set -x' for debugging (prints each command before execution).
Structure script logically: parse arguments and validate input first, define functions for reusable code, main script logic, cleanup on exit using trap. Example:
```bash
trap cleanup EXIT
function cleanup() { rm -f "$TEMP_FILE"; }
function usage() { echo "Usage: $0 <arg>"; exit 1; }
[ $# -eq 0 ] && usage
main_logic_here
```
Style conventions: use meaningful variable names in UPPER_CASE for constants, lower_case for local variables, use functions for repeated code, comment complex logic, validate inputs before use, check exit status of important commands, provide helpful error messages with context, and use constants for file paths and configuration. Indent consistently (2 or 4 spaces), use snake_case for function names, and quote variables consistently.
Error handling: check critical command results: if ! command; then echo "Error: command failed"; exit 1; fi. Validate file existence: [ -f "$FILE" ] || { echo "File not found"; exit 1; }. Provide usage help: if [ $# -ne 2 ]; then echo "Usage: $0 arg1 arg2"; exit 1; fi. Log errors to stderr: echo "Error" >&2. Understanding these practices creates maintainable, reliable scripts.
220. Explain variable scope in bash including local vs global variables, environment variables, and readonly variables.
Difficulty: HardType: SubjectiveTopic: Shell Variables
Global variables by default: any variable assigned at top level is accessible throughout script and sub-functions. Example: VAR=value at script level is global. Changes in functions affect global scope unless declared local. This can cause unintended side effects if functions modify global variables.
Local variables declared with 'local' keyword inside functions are only accessible within that function, preventing pollution of global namespace. Example:
```bash
function test() {
local LOCAL_VAR="function scope"
GLOBAL_VAR="modified globally"
}
```
LOCAL_VAR isn't accessible outside function, GLOBAL_VAR modifies global variable or creates it if didn't exist.
Environment variables exported with 'export' are passed to child processes (subshells, executed commands). Example: export PATH=$PATH:/new/path makes PATH available to all subsequent commands. Declare and export together: export VAR=value. Child processes inherit exported variables but changes in child don't affect parent. Check environment: env shows all exported variables, printenv VARNAME shows specific variable.
Readonly variables can't be modified after creation: readonly CONST=value or declare -r CONST=value. Attempting modification causes error. Use for constants like configuration values that shouldn't change. Unset doesn't work on readonly variables. Readonly -p lists all readonly variables.
Special variables: $HOME (home directory), $USER (username), $PWD (current directory), $OLDPWD (previous directory), $PATH (executable search path), $SHELL (default shell), $$ (current process PID), $! (last background process PID). These are typically environment variables set by shell or system.
Best practices: use local for function variables preventing side effects, export only variables needed by child processes, use readonly for true constants, prefix global variables with descriptive names avoiding conflicts, and document variable scope in complex scripts. Understanding scope prevents hard-to-debug issues from variable conflicts.
221. Explain how to read user input and handle output in shell scripts including read command, echo, printf, and here documents.
Difficulty: MediumType: SubjectiveTopic: Pipes Redirects
Read user input with read command: read VAR prompts for input and stores in VAR. Prompt with -p: read -p "Enter name: " NAME. Silent input (passwords): read -s PASSWORD. Read multiple variables: read VAR1 VAR2 splits input on whitespace. Read line with spaces: read -r LINE (raw mode prevents backslash interpretation). Timeout: read -t 5 times out after 5 seconds.
Advanced read: read array items with read -a ARRAY splitting into array, read from file with while IFS= read -r line; do echo "$line"; done < file.txt. Default variable: read without variable stores in $REPLY. Read with delimiter: read -d ':' VAR reads until colon. Handle empty input: read VAR || VAR="default".
Output with echo: echo "text" outputs with newline, echo -n "text" suppresses newline, echo -e "text\nmore" interprets escape sequences (\n, \t, etc.). Echo is simple but printf offers more control: printf "%s\n" "$VAR" formats output, printf "%-20s %d\n" "$NAME" "$AGE" formats columns with width specification, printf "%03d\n" 5 outputs 005 with zero padding.
Here documents for multi-line input: cat << EOF creates multi-line content until EOF delimiter. Expand variables: cat << EOF hello $USER EOF expands $USER. Prevent expansion: cat << 'EOF' or cat << \EOF. Common for generating config files: cat << EOF > config.txt content here EOF writes to file. Indent with <<-: cat <<- EOF strips leading tabs (not spaces).
Output redirection: echo "text" > file overwrites, echo "text" >> file appends. Tee for both file and stdout: echo "text" | tee file shows and saves. Redirect stderr: echo "error" >&2 sends to stderr. Suppress output: command > /dev/null 2>&1. Understanding input/output makes scripts interactive and handles data flow effectively.
222. Explain different command chaining operators: semicolon (;), AND (&&), OR (||), and pipe (|). Provide examples of when to use each.
Difficulty: MediumType: SubjectiveTopic: Command Chaining
Semicolon (;) executes commands sequentially regardless of success or failure: command1; command2; command3 runs all commands in order. Second command runs even if first fails. Use for independent commands where each should run regardless of previous results. Example: cd /tmp; ls lists /tmp even if cd failed (if already in /tmp).
AND operator (&&) executes next command only if previous succeeded (exit status 0): command1 && command2 runs command2 only if command1 succeeds. Use for dependent operations where second command should only run if first succeeds. Example: mkdir backup && cp file backup/ only copies if directory creation succeeds. Chain multiple: command1 && command2 && command3.
OR operator (||) executes next command only if previous failed (non-zero exit status): command1 || command2 runs command2 only if command1 fails. Use for fallbacks or error handling. Example: test -f file || touch file creates file only if doesn't exist. Common pattern: command || { echo "Error"; exit 1; } provides error handling.
Pipe (|) connects stdout of one command to stdin of next, creating data processing pipelines: command1 | command2 | command3. Data flows through commands. Use for filtering, transforming, or processing command output. Example: cat file | grep pattern | sort | uniq processes file through multiple filters.
Combining operators: cd /tmp && ls || echo "Failed" changes to /tmp, lists contents if cd succeeded, otherwise prints error. Parentheses create subshells for grouping: (command1 && command2) || command3 runs command3 if either in parentheses fails. Understanding chaining creates sophisticated command sequences handling success/failure appropriately.
223. Explain file testing operators in bash. How do you check if files exist, are readable, writable, directories, etc.?
Difficulty: HardType: SubjectiveTopic: Shell Operators
File test operators used with test command ([ ]) or [[ ]]: -e file tests if file exists (any type), -f file tests if regular file exists, -d file tests if directory exists, -L file tests if symbolic link exists, -b file tests if block device, -c file tests if character device, -p file tests if named pipe, -S file tests if socket.
Permission tests: -r file tests if readable, -w file tests if writable, -x file tests if executable, -O file tests if owned by current user, -G file tests if owned by current group. These check effective permissions considering user, group, and others.
File comparison: file1 -nt file2 tests if file1 newer than file2 (modification time), file1 -ot file2 tests if older, -ef tests if same file (same inode). Size test: -s file tests if file has size greater than zero (non-empty). Example:
```bash
if [ -f "$FILE" ] && [ -r "$FILE" ]; then
cat "$FILE"
else
echo "File doesn't exist or not readable"
fi
```
Combining tests: use && (AND), || (OR), ! (NOT). Example: [ -f file ] && [ ! -w file ] tests if file exists and not writable. In [[ ]], use built-in && and ||: [[ -f file && -r file ]]. The [[ ]] construct is bash-specific but more powerful than [ ], supporting pattern matching and regex.
Common patterns: check before operations [ -d "$DIR" ] || mkdir "$DIR" creates directory if doesn't exist, [ ! -f "$FILE" ] && touch "$FILE" creates file if doesn't exist, validate input: [ -z "$VAR" ] tests if variable empty. Proper file testing prevents errors from missing files, wrong permissions, or incorrect file types.
224. Explain string manipulation in bash including concatenation, substring extraction, pattern matching, and replacement.
Difficulty: HardType: SubjectiveTopic: Shell Operators
String concatenation: simply place strings together: STR="$VAR1$VAR2" or STR="${VAR1}text${VAR2}". No special operator needed. Append to string: STR="$STR more text" or STR+=" more text" (bash-specific). Quotes handle spaces: STR="$VAR1 $VAR2" includes space.
String length: ${#VAR} returns length. Example: VAR="hello"; echo ${#VAR} outputs 5. Useful for validation: if [ ${#INPUT} -lt 3 ]; then echo "Too short"; fi.
Substring extraction: ${VAR:offset:length} extracts substring. VAR="hello world"; ${VAR:0:5} gives "hello", ${VAR:6} gives "world" (from position 6 to end), ${VAR: -5} gives "world" (last 5 chars, note space before -). Offset 0-indexed.
Pattern matching and removal: ${VAR#pattern} removes shortest match from beginning, ${VAR##pattern} removes longest match from beginning, ${VAR%pattern} removes shortest match from end, ${VAR%%pattern} removes longest match from end. Example: FILE="path/to/file.txt"; ${FILE##*/} gives "file.txt" (basename), ${FILE%.*} gives "path/to/file" (remove extension).
String replacement: ${VAR/pattern/replacement} replaces first match, ${VAR//pattern/replacement} replaces all matches. Example: PATH="/home/user"; ${PATH/home/opt} gives "/opt/user". Case conversion (bash 4+): ${VAR^} uppercases first char, ${VAR^^} uppercases all, ${VAR,} lowercases first, ${VAR,,} lowercases all.
Default values: ${VAR:-default} returns default if VAR unset/empty, ${VAR:=default} assigns default if unset/empty, ${VAR:?error} exits with error if unset/empty. Example: OUTPUT=${1:-output.txt} uses first arg or default. Understanding string operations enables text processing without external commands like sed or awk.
225. How do you perform arithmetic operations in bash? Explain different methods and their use cases.
Difficulty: MediumType: SubjectiveTopic: Shell Operators
Bash arithmetic expansion using $(( expression )): performs integer arithmetic. Operators: + (addition), - (subtraction), * (multiplication), / (integer division), % (modulus), ** (exponentiation). Example: RESULT=$((5 + 3)) assigns 8, RESULT=$((10 / 3)) assigns 3 (integer division). Variables don't need $ inside (( )): RESULT=$((VAR1 + VAR2)).
Increment/decrement: ((VAR++)) increments, ((VAR--)) decrements, ((VAR+=5)) adds 5. Assignment operators: +=, -=, *=, /=, %=. Comparison returns 0 (false) or 1 (true): (( 5 > 3 )) returns true. Use in conditionals: if (( VAR > 10 )); then echo "Greater"; fi.
Let command alternative: let "RESULT=5+3" or let RESULT=5+3 (no quotes if no spaces). Multiple operations: let "X=5" "Y=10" "Z=X+Y". Can use without assigning: let "counter++".
Expr command for portability (POSIX): RESULT=$(expr 5 + 3) requires spaces around operators. Multiplication needs escaping: expr 5 \* 3. Less efficient than $(( )) due to external command, but works in all shells.
Floating-point arithmetic: bash only supports integers, use bc or awk for decimals. Example: RESULT=$(echo "scale=2; 10/3" | bc) gives 3.33 with 2 decimal places. Awk: RESULT=$(awk "BEGIN {print 10/3}").
Random numbers: $RANDOM generates random integer 0-32767. Range: RAND=$((RANDOM % 100)) gives 0-99. Seed: RANDOM=seed sets seed for reproducible sequence.
Common patterns: loop counter: for ((i=0; i<10; i++)); do echo $i; done. Calculate percentage: PERCENT=$((VALUE * 100 / TOTAL)). Understanding arithmetic enables numeric processing, counters, calculations, and mathematical operations in scripts.
226. What techniques and tools can you use to debug shell scripts? Explain various debugging approaches.
Difficulty: HardType: SubjectiveTopic: Script Debugging
Set -x enables debug mode printing each command before execution with expanded variables: set -x at script start or bash -x script.sh runs entire script in debug. Disable with set +x. Output prefixed with +. Helps trace execution flow and see actual values. Use PS4 variable to customize prefix: export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' shows file, line, and function.
Set -v (verbose) prints script lines as read before execution, showing raw commands. Combine: set -xv shows both raw and expanded. Set -e exits on first error, set -u exits on undefined variables, set -o pipefail fails on pipeline errors. Together: set -euxo pipefail creates strict mode catching most errors.
Strategic echo statements: add echo "Reached checkpoint 1" at key points, echo "VAR=$VAR" shows variable values, echo "$(date): processing $FILE" adds timestamps. Redirect debug output to file: exec 5> debug.log; BASH_XTRACEFD=5; set -x sends trace to file descriptor 5 instead of stderr.
Validation and testing: check exit status: command; echo $? shows return code, test command availability: command -v cmd tests if command exists, validate variables: [ -z "$VAR" ] && { echo "Error: VAR empty"; exit 1; }, verify file operations: [ -f "$FILE" ] || { echo "File not found"; exit 1; }.
Shellcheck is lint tool for shell scripts finding bugs, deprecated syntax, and suggesting improvements: shellcheck script.sh. Install and run on all scripts. Explains errors with wiki links. Bash -n script.sh checks syntax without executing.
Interactive debugging: trap 'read -p "Paused at line $LINENO. Press enter to continue..."' DEBUG pauses at each line. Function for debugging: debug() { [ "$DEBUG" ] && echo "DEBUG: $*" >&2; }; DEBUG=1 for debug mode. Use logging functions categorizing messages by severity. Understanding debugging techniques quickly identifies and fixes script issues.
227. What is the correct syntax for an if statement in bash?
Difficulty: EasyType: MCQTopic: Conditional Logic
- if [ condition ]; then commands; fi
- if (condition) { commands }
- if condition: commands endif
- if [condition] then commands end
Bash if statement syntax: if [ condition ]; then commands; fi. The spaces around brackets are required. Semicolon or newline separates condition from then. Alternative format:
```bash
if [ condition ]
then
commands
fi
```
Both formats valid, choose based on readability preference.
Add else: if [ condition ]; then commands1; else commands2; fi. Add elif for multiple conditions: if [ cond1 ]; then cmd1; elif [ cond2 ]; then cmd2; else cmd3; fi. Test command [ ] is equivalent to test command: if test condition; then commands; fi. Modern bash prefers [[ ]] with more features: [[ $VAR == pattern ]] supports pattern matching.
Common conditions: [ "$VAR" = "value" ] string equality, [ $NUM -eq 5 ] numeric equality, [ -f file ] file exists, [ $A -gt $B ] greater than. Always quote variables to handle empty values safely: [ "$VAR" = "value" ] prevents errors if VAR empty. Understanding if statements is fundamental for conditional logic in scripts.
Correct Answer: if [ condition ]; then commands; fi
228. What is the case statement used for in bash?
Difficulty: MediumType: MCQTopic: Case Statement
- Multi-way branching based on pattern matching
- Converting text case
- Error handling
- Loop control
Case statement provides multi-way branching matching variable against patterns, cleaner than multiple if-elif for many conditions. Syntax:
```bash
case $VAR in
pattern1)
commands
;;
pattern2)
commands
;;
*)
default commands
;;
esac
```
Each pattern ends with ), commands end with ;;. Asterisk (*) is catch-all default.
Patterns support wildcards: abc matches exact string, a* matches strings starting with a, [abc] matches single character a, b, or c, {a,b,c} matches a, b, or c. Multiple patterns: pattern1|pattern2) matches either. Example:
```bash
case $OPTION in
start|begin)
echo "Starting"
;;
stop|end)
echo "Stopping"
;;
*)
echo "Unknown option"
;;
esac
```
Use ;& (fall-through) or ;;& (test next pattern) for advanced control in bash 4+. Case statements excellent for menu systems, command-line option parsing, or handling multiple conditions. More readable than long if-elif chains when checking single variable against many values.
Correct Answer: Multi-way branching based on pattern matching
229. Which is the correct syntax for a for loop in bash?
Difficulty: EasyType: MCQTopic: Shell Loops
- for VAR in list; do commands; done
- for (VAR in list) { commands }
- foreach VAR in list: commands endfor
- for VAR = list do commands end
For loop syntax: for VAR in list; do commands; done. Alternative format:
```bash
for VAR in list
do
commands
done
```
VAR takes each value from list sequentially. List can be explicit: for i in 1 2 3; do echo $i; done, or generated from commands: for file in *.txt; do echo $file; done.
Common patterns: loop through files for file in /path/*; do echo "$file"; done, loop through array for item in "${ARRAY[@]}"; do echo "$item"; done, loop through command output for user in $(cat users.txt); do echo $user; done. Use "$@" for script arguments: for arg in "$@"; do echo "$arg"; done.
C-style for loop (bash-specific): for ((i=0; i<10; i++)); do echo $i; done. Useful for numeric ranges with counter control. Ranges with brace expansion: for i in {1..10}; do echo $i; done generates 1 through 10. Step with {start..end..step}: for i in {0..100..10}; do echo $i; done counts by tens.
Break exits loop early, continue skips to next iteration. Understanding for loops enables iteration over files, arrays, ranges, and command output in scripts.
Correct Answer: for VAR in list; do commands; done
230. What does a while loop do in bash?
Difficulty: MediumType: MCQTopic: Shell Loops
- Executes commands repeatedly while condition is true
- Executes commands once
- Only works with numbers
- Same as for loop
While loop executes commands repeatedly as long as condition is true (returns 0). Syntax: while [ condition ]; do commands; done. Example:
```bash
COUNT=0
while [ $COUNT -lt 5 ]; do
echo $COUNT
((COUNT++))
done
```
Tests condition before each iteration, may never execute if initially false.
Read file line by line (common pattern): while IFS= read -r line; do echo "$line"; done < file.txt. IFS= preserves leading/trailing whitespace, -r prevents backslash interpretation. Read from command: command | while read var; do echo "$var"; done. Note: variables modified in pipeline while loop don't affect parent shell (runs in subshell).
Infinite loop: while true; do commands; done or while :; do commands; done. Exit with break or when condition becomes false. Until loop is opposite: until [ condition ]; do commands; done executes while condition is false, stops when true.
Use while for condition-based iteration (unknown number of iterations), counters with complex logic, reading files line-by-line, or waiting for conditions. Understanding while loops enables flexible iteration based on dynamic conditions.
Correct Answer: Executes commands repeatedly while condition is true
231. How do you define a function in bash?
Difficulty: MediumType: MCQTopic: Shell Functions
- function name() { commands; } or name() { commands; }
- def name(): commands
- function name commands end
- create function name { commands }
Function definition: function name() { commands; } or simply name() { commands; }. Both forms equivalent. Example:
```bash
function greet() {
echo "Hello, $1"
}
# or
greet() {
echo "Hello, $1"
}
```
Call with arguments: greet "World" outputs "Hello, World".
Function arguments: $1, $2, etc. are function parameters, not script parameters. $@ and $# work within function scope. Local variables: local VAR=value creates variable local to function, preventing modification of global scope. Return status with return N (0-255), or use echo for return values: RESULT=$(function_name).
Functions can call other functions, including recursively. Define functions before calling them in script. Organize related commands into functions for reusability. Example:
```bash
check_file() {
local file=$1
if [ -f "$file" ]; then
return 0
else
return 1
fi
}
if check_file "test.txt"; then
echo "File exists"
fi
```
Functions improve code organization, enable code reuse, make scripts more maintainable, and allow testing individual components. Understanding functions is essential for writing modular, professional scripts.
Correct Answer: function name() { commands; } or name() { commands; }
232. How do you declare and access array elements in bash?
Difficulty: HardType: MCQTopic: Shell Arrays
- Declare: ARRAY=(val1 val2 val3), Access: ${ARRAY[index]}
- Declare: ARRAY[val1, val2, val3], Access: ARRAY[index]
- Declare: array ARRAY = [val1, val2, val3], Access: ARRAY.index
- Bash doesn't support arrays
Array declaration: ARRAY=(val1 val2 val3) or ARRAY[0]=val1; ARRAY[1]=val2. Access elements: ${ARRAY[0]} (first element), ${ARRAY[1]} (second), etc. Indices are 0-based. Without index, ${ARRAY} returns first element. All elements: "${ARRAY[@]}" expands to separate words, "${ARRAY[*]}" expands to single word.
Array length: ${#ARRAY[@]} returns number of elements, ${#ARRAY[0]} returns length of first element. Append: ARRAY+=(new_element). Slice: ${ARRAY[@]:start:length} extracts elements. Example: ${ARRAY[@]:1:2} gets 2 elements starting at index 1. Unset element: unset ARRAY[2] removes element at index 2.
Iterate array: for item in "${ARRAY[@]}"; do echo "$item"; done. With indices: for i in "${!ARRAY[@]}"; do echo "$i: ${ARRAY[$i]}"; done. Read into array: readarray -t ARRAY < file.txt or mapfile -t ARRAY < file.txt loads file lines into array.
Associative arrays (bash 4+): declare -A ASSOC creates associative array (key-value pairs). Access: ASSOC[key]=value, ${ASSOC[key]}. Keys: ${!ASSOC[@]}. Example:
```bash
declare -A CONFIG
CONFIG[host]="localhost"
CONFIG[port]=8080
echo ${CONFIG[host]}
```
Understanding arrays enables handling multiple values, processing lists, and building complex data structures in scripts.
Correct Answer: Declare: ARRAY=(val1 val2 val3), Access: ${ARRAY[index]}
233. What does the select statement do in bash?
Difficulty: MediumType: MCQTopic: Script Arguments
- Creates interactive menu for user selection
- Selects files from directory
- Chooses fastest command
- Filters output
Select creates numbered interactive menu from list, prompting user to choose option. Syntax:
```bash
select VAR in option1 option2 option3; do
case $VAR in
option1) commands; break;;
option2) commands; break;;
*) echo "Invalid";;
esac
done
```
Displays numbered list, reads user input, sets VAR to selected value. Loop continues until break.
Customize prompt with PS3 variable: PS3="Choose option: " select VAR in opt1 opt2; do ... done. Selected index in $REPLY. Combine with case for handling selections. Break exits select loop, useful after processing choice.
Practical menu example:
```bash
PS3="Select operation: "
select op in "Backup" "Restore" "Exit"; do
case $op in
Backup) backup_function; break;;
Restore) restore_function; break;;
Exit) break;;
*) echo "Invalid option";;
esac
done
```
Select useful for interactive scripts, setup wizards, configuration tools, or any script requiring user choice from predefined options. Provides clean interface without manual menu implementation. Understanding select simplifies creating user-friendly interactive scripts.
Correct Answer: Creates interactive menu for user selection
234. What is getopts used for in bash scripts?
Difficulty: HardType: MCQTopic: Script Arguments
- Parsing command-line options and arguments
- Getting system configuration
- Optimizing script performance
- Managing processes
Getopts parses command-line options (-a, -b, etc.) providing standard interface for script options. Syntax: while getopts "optstring" VAR; do ... done. Optstring defines valid options, colon after option indicates it requires argument. Example: "ab:c" accepts -a, -b with argument, -c. Current option in $VAR, argument in $OPTARG.
Example:
```bash
while getopts "f:o:v" opt; do
case $opt in
f) INPUT_FILE=$OPTARG;;
o) OUTPUT_FILE=$OPTARG;;
v) VERBOSE=1;;
\?) echo "Invalid option"; exit 1;;
esac
done
shift $((OPTIND-1)) # Remove processed options
# Remaining arguments in $@
```
Getopts handles: option bundling (-abc same as -a -b -c), option arguments (-f file or -ffile), invalid option errors (?), required argument errors (:). Leading colon in optstring enables silent error reporting: while getopts ":ab:" opt enables custom error handling.
Advantages over manual parsing: standard behavior, handles edge cases, cleaner code. Limitations: only single-character options (use getopt command for long options like --help). Understanding getopts enables professional command-line interfaces matching Unix conventions.
Correct Answer: Parsing command-line options and arguments
235. Explain the differences between [ ], [[ ]], and (( )) for conditionals in bash. When should you use each?
Difficulty: HardType: SubjectiveTopic: Conditional Logic
Single brackets [ ] are the traditional test command, POSIX-compatible working in all shells. Requires careful quoting of variables to prevent word splitting: [ "$VAR" = "value" ]. Spaces around brackets and operators required. Operators: = or == for string equality, != for inequality, -eq, -ne, -gt, -lt, -ge, -le for numeric comparison. Combine with -a (AND), -o (OR), ! (NOT).
Double brackets [[ ]] are bash-specific with enhanced features: pattern matching [[ $VAR == pattern ]], regex matching [[ $VAR =~ regex ]], no word splitting (quotes often optional), && and || operators instead of -a/-o, no pathname expansion inside. Example: [[ $FILE == *.txt ]] checks if FILE ends with .txt without needing quotes. More forgiving and powerful but not POSIX-portable.
Double parentheses (( )) for arithmetic evaluation: supports C-style operators (+, -, *, /, %, ++, --), comparison operators (>, <, >=, <=, ==, !=), logical operators (&&, ||, !), no need for $ on variables inside. Example: if (( VAR > 10 )); then echo "Greater"; fi. Returns true (0) if expression is non-zero. Use for all numeric comparisons and calculations.
Comparison:
- [ ] most portable, use for POSIX scripts or maximum compatibility
- [[ ]] most powerful for bash, use when bash-specific features needed (pattern matching, regex)
- (( )) for arithmetic, use for all numeric operations and comparisons
Best practices: use [[ ]] in bash scripts for string operations and file tests (cleaner, more powerful), use (( )) for numeric operations (clearer intent, proper arithmetic), use [ ] only when POSIX portability required. Understanding these differences enables writing correct, efficient conditional logic.
236. Explain advanced loop patterns including nested loops, break/continue, loop control with signals, and reading files efficiently.
Difficulty: HardType: SubjectiveTopic: Shell Loops
Nested loops: loops inside loops, each with own iteration variable. Example:
```bash
for i in {1..3}; do
for j in {a..c}; do
echo "$i$j"
done
done
```
Produces combinations. Track depth carefully, use meaningful variable names. Break exits innermost loop, break N exits N levels of nested loops.
Break and continue: break exits loop entirely, continue skips remaining commands and starts next iteration. Use for early exit on conditions or skipping invalid data:
```bash
for file in *.txt; do
[ -r "$file" ] || continue # Skip unreadable files
process "$file"
done
```
Efficient file reading: avoid cat in loop (useless use of cat). Good: while read line; do echo "$line"; done < file. Bad: cat file | while read line. Process substitution: while read line; do ... done < <(command). Read multiple columns: while read col1 col2 col3; do ... done < file splits on whitespace.
Reading with IFS: while IFS=: read user pass uid gid; do echo "$user"; done < /etc/passwd splits on colons. Preserve whitespace: while IFS= read -r line ensures leading/trailing spaces kept, backslashes not interpreted. Handle last line without newline: while IFS= read -r line || [ -n "$line" ]; do ... done.
Loop optimization: minimize external commands in loops (slow), use built-ins when possible, process in batches for large datasets, consider awk/sed for text processing instead of loops. Monitor progress in long loops: ((count++ % 100 == 0)) && echo "Processed $count items". Understanding loop patterns enables efficient data processing.
237. Explain advanced function concepts including return values, variable scope, function libraries, and recursive functions.
Difficulty: HardType: SubjectiveTopic: Shell Functions
Return values: functions return exit status (0-255) via return N, not actual values. Get output with command substitution: RESULT=$(function_name). Echo values in function: function get_value() { echo "result"; }, VALUE=$(get_value). Multiple return values: echo space-separated values, split with read: read var1 var2 <<< "$(function)".
Variable scope: variables are global by default, visible everywhere. Local variables with local keyword exist only in function:
```bash
function test() {
local LOCAL_VAR="function scope"
GLOBAL_VAR="modified globally"
}
test
echo $GLOBAL_VAR # Visible
echo $LOCAL_VAR # Empty
```
Use local for all function variables preventing side effects. Export doesn't affect function scope (only child processes).
Function libraries: source or . loads functions from external files. Create library file:
```bash
# lib/common.sh
log() { echo "[$(date)] $*"; }
error() { echo "ERROR: $*" >&2; exit 1; }
```
Source in scripts: source lib/common.sh or . lib/common.sh. Check file exists: [ -f lib/common.sh ] && source lib/common.sh || { echo "Library not found"; exit 1; }. Organize related functions into libraries for reuse across scripts.
Recursive functions: function calls itself. Example factorial:
```bash
factorial() {
local n=$1
if ((n <= 1)); then
echo 1
else
echo $((n * $(factorial $((n-1)))))
fi
}
```
Need base case to prevent infinite recursion. Use for tree traversal, directory processing, or algorithms naturally recursive. Bash has limited stack depth (~1000 levels). For deep recursion, consider iteration or external programs.
Best practices: one function, one purpose; meaningful names; document parameters and return values; handle errors; validate inputs; use local variables; return early on errors; keep functions short (<50 lines). Understanding advanced function usage enables writing modular, maintainable, professional scripts.
238. Explain advanced array operations including sorting, searching, filtering, and transforming arrays in bash.
Difficulty: HardType: SubjectiveTopic: Shell Arrays
Array sorting: bash has no built-in sort, use external sort command:
```bash
ARRAY=(banana apple cherry)
IFS=$'\n' SORTED=($(sort <<< "${ARRAY[*]}"))
unset IFS
```
Reads array into sort, captures output into new array. Numeric sort: sort -n. Reverse: sort -r. For large arrays, write to file, sort, read back.
Searching arrays: loop through and compare:
```bash
contains() {
local item=$1
shift
for element in "$@"; do
[[ $element == "$item" ]] && return 0
done
return 1
}
contains "apple" "${ARRAY[@]}" && echo "Found"
```
For associative arrays, check key: [[ -v ASSOC[key] ]] tests if key exists.
Filtering arrays: create new array with matching elements:
```bash
ORIG=(apple banana apricot cherry)
FILTERED=()
for item in "${ORIG[@]}"; do
[[ $item == a* ]] && FILTERED+=("$item")
done
```
Filters items starting with 'a'. Use pattern matching, regex, or custom conditions.
Transforming arrays: apply operation to each element:
```bash
NUMS=(1 2 3 4 5)
SQUARES=()
for n in "${NUMS[@]}"; do
SQUARES+=($((n * n)))
done
```
Map operation creating new array. In-place: NUMS[i]=$(process "${NUMS[i]}").
Array joining: IFS=, joined="${ARRAY[*]}" joins with comma. Splitting: IFS=, read -ra ARRAY <<< "$string" splits string on comma. Removing elements: unset ARRAY[index] removes specific element (creates sparse array), or rebuild: NEW_ARRAY=(${ARRAY[@]:0:index} ${ARRAY[@]:$((index+1))}) removes element.
Array copying: COPY=("${ARRAY[@]}") creates shallow copy. Associative array: for key in "${!ASSOC[@]}"; do NEW_ASSOC[$key]=${ASSOC[$key]}; done. Understanding array operations enables complex data manipulation in pure bash.
239. Explain glob patterns and extended pattern matching in bash. How do they differ from regular expressions?
Difficulty: HardType: SubjectiveTopic: Wildcards Globbing
Glob patterns for pathname expansion: * matches zero or more characters, ? matches single character, [abc] matches one of a, b, c, [a-z] matches range, [!abc] matches any except a, b, c. Examples: *.txt matches all .txt files, file?.txt matches file1.txt but not file10.txt, [A-Z]*.txt matches uppercase-starting txt files.
Extended globbing (enable with shopt -s extglob): ?(pattern) matches zero or one occurrence, *(pattern) matches zero or more, +(pattern) matches one or more, @(pattern) matches exactly one, !(pattern) matches anything except pattern. Examples: ?(*.txt) matches .txt files or nothing, +(digit).txt matches digit followed by one or more digits, !(*.txt) matches everything except .txt files.
Brace expansion: {a,b,c} expands to a b c, {1..10} expands to 1 through 10, {a..z} expands to alphabet. Combine: file{1..3}.txt expands to file1.txt file2.txt file3.txt. Useful for batch operations: mkdir dir{1..5} creates five directories.
Globs vs regex: globs for filename matching (pathname expansion), regex for text pattern matching. Globs: * means zero or more of any character. Regex: .* means zero or more of any character (* quantifier for previous atom). Globs: ? means one character. Regex: . means one character, ? makes previous optional.
Regex in bash: [[ ]] supports regex with =~ operator: [[ $VAR =~ ^[0-9]+$ ]] matches VAR contains only digits. Capture groups: BASH_REMATCH[0] is full match, BASH_REMATCH[1] is first capture group. Example:
```bash
if [[ $EMAIL =~ ^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$ ]]; then
echo "User: ${BASH_REMATCH[1]}"
echo "Domain: ${BASH_REMATCH[2]}"
fi
```
Use globs for file operations, regex for text validation and parsing. Understanding pattern matching enables powerful file selection and text processing.
240. Explain advanced parameter expansion techniques in bash including default values, pattern substitution, substring extraction, and case modification.
Difficulty: HardType: SubjectiveTopic: Shell Parameters
Default values: ${VAR:-default} returns default if VAR unset or empty (doesn't modify VAR), ${VAR:=default} assigns default if unset/empty (modifies VAR), ${VAR:+alternate} returns alternate if VAR set (opposite of :-), ${VAR:?error} exits with error message if unset/empty. Examples:
```bash
FILE=${1:-input.txt} # Use $1 or default
PORT=${PORT:=8080} # Set PORT to 8080 if not set
: ${DIR:=/tmp} # Idiom for setting defaults
```
String length and substrings: ${#VAR} returns length, ${VAR:offset} extracts from offset to end, ${VAR:offset:length} extracts length characters from offset, ${VAR: -5} extracts last 5 characters (note space before minus). Example: FILE="path/to/file.txt"; NAME="${FILE##*/}"; EXT="${FILE##*.}".
Pattern removal: ${VAR#pattern} removes shortest match from beginning, ${VAR##pattern} removes longest match from beginning, ${VAR%pattern} removes shortest match from end, ${VAR%%pattern} removes longest match from end. Examples:
```bash
FILE="/path/to/file.tar.gz"
DIR=${FILE%/*} # /path/to (remove filename)
NAME=${FILE##*/} # file.tar.gz (basename)
BASE=${FILE%%.*} # /path/to/file (remove all extensions)
EXT=${FILE##*.} # gz (last extension)
```
Pattern substitution: ${VAR/pattern/replacement} replaces first match, ${VAR//pattern/replacement} replaces all matches, ${VAR/#pattern/replacement} replaces at beginning only, ${VAR/%pattern/replacement} replaces at end only. Examples:
```bash
PATH="/usr/local/bin:/usr/bin"
NEW_PATH=${PATH//bin/sbin} # Replace all 'bin' with 'sbin'
STR="Hello World"
LOWER=${STR,,} # Convert to lowercase (bash 4+)
UPPER=${STR^^} # Convert to uppercase
CAPITAL=${STR^} # Capitalize first char
```
Case modification (bash 4+): ${VAR^} uppercases first character, ${VAR^^} uppercases all, ${VAR,} lowercases first, ${VAR,,} lowercases all, ${VAR~} toggles case of first, ${VAR~~} toggles all.
Indirection: ${!VAR} expands to value of variable named in VAR. Example: KEY="PATH"; echo ${!KEY} prints PATH's value. Indirect array: keys="!ARRAY[@]"; for key in ${!keys}; do echo $key; done.
Understanding parameter expansion eliminates need for external commands like basename, dirname, cut, sed for many string operations, making scripts faster and more portable.
241. Explain process substitution in bash. How does it differ from command substitution and when should you use it?
Difficulty: HardType: SubjectiveTopic: Command Substitution
Process substitution treats command output as file using <(command) for reading or >(command) for writing. Bash creates temporary FIFO (named pipe) or /dev/fd/ file descriptor connected to command output/input. Syntax: <(command) creates readable file, >(command) creates writable file. Use when commands expect files but you have command output.
Examples:
```bash
# Compare outputs of two commands
diff <(ls dir1) <(ls dir2)
# Sort and compare without temp files
comm <(sort file1) <(sort file2)
# Feed command output to multiple commands
tee >(process1) >(process2) < input
# Read from multiple sources
while read line; do echo "$line"; done < <(cat file1 file2)
```
Difference from command substitution $(): command substitution captures output as string for variable assignment or inline use: VAR=$(command) or echo "Result: $(command)". Process substitution creates file-like interface for commands expecting file arguments. Command substitution stores all output in memory, process substitution streams data through pipe.
Use cases: commands requiring file arguments (diff, comm, paste, join), avoiding temporary files, parallel processing (multiple outputs with tee), reading output preserving while loop variables (avoiding subshell issue). Example:
```bash
# This works (process substitution avoids subshell)
while read line; do
COUNT=$((COUNT+1))
done < <(cat file)
echo "Lines: $COUNT" # COUNT visible
# This doesn't (pipe creates subshell)
cat file | while read line; do
COUNT=$((COUNT+1))
done
echo "Lines: $COUNT" # COUNT not visible
```
Limitations: not POSIX portable (bash, zsh, ksh only), may not work with commands checking file type, order of execution may differ from expectation. Understanding process substitution enables advanced I/O manipulation without temporary files, cleaner code, and solves subshell variable visibility issues.
242. What are best practices for organizing large shell scripts? Discuss structure, modularity, and maintainability.
Difficulty: MediumType: SubjectiveTopic: Shell Scripting
Structure template:
```bash
#!/bin/bash
# Script header: description, usage, author, version
set -euo pipefail # Strict mode
# Constants (UPPERCASE)
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_NAME="$(basename "$0")"
readonly CONFIG_FILE="${SCRIPT_DIR}/config.conf"
# Default variables (lowercase)
verbose=0
log_file="/var/log/${SCRIPT_NAME}.log"
# Functions
usage() { ... }
log() { ... }
error() { ... }
validate_input() { ... }
main() { ... }
# Parse arguments
while getopts "vhf:" opt; do ...; done
# Main execution
main "$@"
```
Modularity: break into logical functions (single responsibility), source common functions from libraries, separate configuration from code, use function names describing action. Group related functions: all validation functions together, all logging functions together, main logic functions.
Library organization:
```
project/
├── bin/
│ └── main_script.sh
├── lib/
│ ├── common.sh # Shared utilities
│ ├── logging.sh # Logging functions
│ └── validation.sh # Input validation
├── conf/
│ └── config.conf
└── README.md
```
Source libraries: source "${SCRIPT_DIR}/../lib/common.sh". Check if sourced: [[ -n ${COMMON_LIB:-} ]] && return prevents double-sourcing.
Configuration management: external config files for environment-specific values, validate config on load, provide defaults, document required variables. Example config.conf:
```bash
# Database config
DB_HOST="localhost"
DB_PORT=5432
DB_NAME="mydb"
```
Load: [ -f "$CONFIG_FILE" ] && source "$CONFIG_FILE" || error "Config not found".
Documentation: header comments explaining purpose and usage, function comments describing parameters and return values, inline comments for complex logic only, usage function showing examples, README for multi-script projects. Version control: use git, tag releases, maintain changelog.
Error handling: validate all inputs, check command exit status for critical operations, provide meaningful error messages with context, log errors to file and stderr, clean up on exit (trap), fail fast with set -e. Testing: unit tests for functions, integration tests for workflows, test error cases, automate testing.
Understanding organization principles makes scripts maintainable, enables collaboration, simplifies debugging, and allows reuse across projects.
243. Where are system logs typically stored in Linux?
Difficulty: EasyType: MCQTopic: Journalctl Logs
- /var/log/
- /etc/log/
- /usr/log/
- /home/log/
System logs stored in /var/log/ directory. Important logs: /var/log/syslog or /var/log/messages (general system messages), /var/log/auth.log (authentication logs), /var/log/kern.log (kernel messages), /var/log/apache2/ or /var/log/httpd/ (web server logs), /var/log/mysql/ (database logs). Logs rotate periodically to prevent disk fill.
View logs: tail -f /var/log/syslog follows log in real-time, grep 'pattern' /var/log/syslog searches logs, journalctl (systemd systems) queries systemd journal. Important for troubleshooting: check logs first when diagnosing issues, errors often logged before visible symptoms.
Log rotation: logrotate manages log rotation based on /etc/logrotate.conf and /etc/logrotate.d/. Rotates by size or time, compresses old logs, deletes old archives. Understanding log locations and management is essential for system troubleshooting and monitoring.
Correct Answer: /var/log/
244. What is the correct format for a crontab entry?
Difficulty: MediumType: MCQTopic: Cron Jobs
- minute hour day month weekday command
- hour minute day month command
- day month year hour minute command
- command minute hour day month
Crontab format: minute (0-59) hour (0-23) day (1-31) month (1-12) weekday (0-7, 0 and 7 are Sunday) command. Example: 30 2 * * * /path/to/script.sh runs at 2:30 AM daily. Special characters: * (any value), */N (every N), N-M (range), N,M (list).
Common patterns: 0 * * * * (every hour), */15 * * * * (every 15 minutes), 0 0 * * 0 (midnight every Sunday), 0 2 1 * * (2 AM on first of month). Special strings: @reboot (at startup), @daily, @weekly, @monthly.
Manage crontab: crontab -e edits user crontab, crontab -l lists entries, crontab -r removes all entries. System-wide: /etc/crontab and /etc/cron.d/. Output: redirect output to file or email sent to user (MAILTO variable).
Debugging: check /var/log/cron or /var/log/syslog for execution, ensure script has execute permissions and correct shebang, use absolute paths in scripts (cron has minimal PATH). Understanding cron enables task automation and scheduled maintenance.
Correct Answer: minute hour day month weekday command
245. What is systemd in modern Linux systems?
Difficulty: HardType: MCQTopic: System Startup
- An init system and service manager that boots the system and manages services
- A system diagnostics tool
- A disk management utility
- A network configuration tool
Systemd is the init system (PID 1) in most modern Linux distributions, replacing older init systems (SysV init, Upstart). Responsibilities: booting system, starting/stopping services, managing dependencies, logging (journald), device management (udev). Units: services (.service), mounts (.mount), timers (.timer), targets (.target, like runlevels).
Boots to target: multi-user.target (multi-user text mode), graphical.target (GUI). View targets: systemctl list-units --type=target. Change: systemctl isolate multi-user.target. Default: systemctl get-default, systemctl set-default graphical.target.
Service management: systemctl start/stop/restart/reload service, systemctl enable/disable (auto-start), systemctl status (show status), systemctl list-units --type=service (list all services). View logs: journalctl -u service.
Older systems use SysV init: scripts in /etc/init.d/, runlevels (0-6), service command or /etc/init.d/script start. Understanding systemd is crucial for managing modern Linux systems.
Correct Answer: An init system and service manager that boots the system and manages services
246. What command creates a new filesystem on a partition?
Difficulty: HardType: MCQTopic: Disk Management
Mkfs (make filesystem) creates filesystem on partition. Syntax: mkfs -t TYPE DEVICE or mkfs.TYPE DEVICE. Types: ext4, xfs, btrfs, vfat. Example: mkfs -t ext4 /dev/sdb1 or mkfs.ext4 /dev/sdb1 creates ext4 filesystem. Warning: destroys existing data.
Partitioning tools: fdisk (MBR partitions), gdisk or parted (GPT partitions), lsblk shows block devices and partitions. Steps: partition disk with fdisk, create filesystem with mkfs, mount with mount, add to /etc/fstab for automatic mounting.
Mount filesystem: mount /dev/sdb1 /mnt/data mounts to directory. Unmount: umount /mnt/data or umount /dev/sdb1. Check mounts: mount or df -h. Persistent: add to /etc/fstab with device, mount point, filesystem type, options, dump, pass fields.
LVM (Logical Volume Manager): provides flexible volume management, create physical volumes (pvcreate), volume groups (vgcreate), logical volumes (lvcreate), resize without unmounting. Understanding disk management is essential for storage administration.
Correct Answer: mkfs
247. Which command shows real-time process and system resource usage?
Difficulty: MediumType: MCQTopic: System Monitoring
Top displays real-time system resource usage and processes, updating every few seconds. Shows: uptime, load average, CPU usage, memory usage, processes sorted by resource consumption. Interactive: k to kill, r to renice, M to sort by memory, P to sort by CPU, q to quit.
Htop is enhanced version with colors, mouse support, tree view, easier process management. Not always installed by default but more user-friendly. Other tools: vmstat (virtual memory stats), iostat (I/O stats), sar (system activity reporter), mpstat (CPU stats per core).
Monitor specific resources: free -h (memory), df -h (disk space), du -sh (directory size), netstat or ss (network connections), iotop (I/O by process), iftop (network traffic by connection). Understanding monitoring tools enables identifying performance bottlenecks and resource constraints.
Correct Answer: top or htop
248. Which command creates compressed archives for backup?
Difficulty: MediumType: MCQTopic: Backup Restore
Tar (tape archive) creates archives, often compressed. Common usage: tar -czf archive.tar.gz /path/to/backup creates compressed archive, tar -xzf archive.tar.gz extracts. Flags: -c (create), -x (extract), -z (gzip compression), -j (bzip2), -J (xz), -f (file), -v (verbose), -t (list contents).
Examples: tar -czf backup-$(date +%Y%m%d).tar.gz /home backs up /home directory, tar -xzf archive.tar.gz -C /restore extracts to specific directory. Exclude: tar --exclude='*.log' -czf archive.tar.gz /data excludes log files.
Other backup tools: rsync (efficient incremental backups), dd (disk cloning), dump/restore (ext filesystem backup), borgbackup (deduplicating backups). Best practices: test backups regularly, store offsite, automate with cron, encrypt sensitive data, document restore procedures.
Backup strategies: full (complete backup), incremental (changes since last backup), differential (changes since last full). 3-2-1 rule: 3 copies, 2 different media, 1 offsite. Understanding backup tools prevents data loss.
Correct Answer: tar
249. What is LVM and what are its main components?
Difficulty: HardType: MCQTopic: LVM Management
- Logical Volume Manager with Physical Volumes, Volume Groups, and Logical Volumes
- Linux Virtual Memory
- Log Volume Management
- Local Volume Mount
LVM (Logical Volume Manager) provides flexible disk management. Components: Physical Volumes (PVs) are physical disks or partitions, Volume Groups (VGs) pool PVs, Logical Volumes (LVs) are virtual partitions created from VGs. Advantages: resize volumes online, span volumes across disks, snapshots for backups.
Create LVM: pvcreate /dev/sdb creates PV, vgcreate vg_data /dev/sdb creates VG, lvcreate -L 10G -n lv_data vg_data creates 10GB LV. Format and mount: mkfs.ext4 /dev/vg_data/lv_data, mount /dev/vg_data/lv_data /data.
Resize: lvextend -L +5G /dev/vg_data/lv_data adds 5GB, resize2fs /dev/vg_data/lv_data resizes filesystem. Shrink: umount first, resize filesystem, then lvreduce. Snapshots: lvcreate -L 1G -s -n snap_data /dev/vg_data/lv_data creates snapshot.
Management commands: pvs/vgs/lvs (display info), pvdisplay/vgdisplay/lvdisplay (detailed), vgextend (add PV to VG), lvremove (remove LV). Understanding LVM enables flexible storage management in enterprise environments.
Correct Answer: Logical Volume Manager with Physical Volumes, Volume Groups, and Logical Volumes
250. What can you do if a Linux system won't boot?
Difficulty: HardType: MCQTopic: System Startup
- Boot from live USB/CD, check logs, repair filesystem, restore bootloader
- Reinstall OS immediately
- Replace hardware
- Nothing can be done
Boot troubleshooting: boot from live USB/CD to access system. Mount root filesystem: mkdir /mnt/root && mount /dev/sda1 /mnt/root. Check /var/log files for errors. Common issues: corrupted filesystem (fsck /dev/sda1 repairs), broken bootloader (grub-install /dev/sda reinstalls), fstab errors (edit /mnt/root/etc/fstab), kernel panic (boot older kernel from GRUB menu).
GRUB rescue: list partitions with ls, set root=(hd0,1), set prefix=(hd0,1)/boot/grub, insmod normal, normal to boot. Then reinstall: grub-install /dev/sda, update-grub. Single-user mode: add single to kernel parameters in GRUB for root shell without password (security risk but useful for recovery).
Chroot: mount system, bind system directories: mount --bind /dev /mnt/root/dev, same for /proc, /sys, /run, then chroot /mnt/root to run commands as if booted. Useful for reinstalling packages, updating config, or fixing broken system.
Prevention: maintain backup kernels, test changes before reboot, keep rescue USB handy, document configuration changes. Understanding boot process and recovery procedures minimizes downtime.
Correct Answer: Boot from live USB/CD, check logs, repair filesystem, restore bootloader
251. Explain how to analyze system logs for troubleshooting. What are common log files and what do they contain?
Difficulty: HardType: SubjectiveTopic: Journalctl Logs
Key log files: /var/log/syslog or /var/log/messages (general system messages from kernel, system daemons, applications), /var/log/auth.log or /var/log/secure (authentication, sudo, SSH login attempts), /var/log/kern.log (kernel messages, hardware issues, driver problems), /var/log/dmesg (boot messages, hardware detection), /var/log/boot.log (service startup during boot).
Application logs: /var/log/apache2/ or /var/log/httpd/ (web server access and error logs), /var/log/mysql/ (database logs), /var/log/nginx/ (nginx logs), /var/log/mail.log (mail server), application-specific directories. Check application documentation for log locations.
Systemd journal: journalctl queries systemd journal (binary format, queryable). Commands: journalctl -xe (recent entries with explanations), journalctl -u service (service-specific), journalctl --since "1 hour ago" (time-based), journalctl -f (follow), journalctl -b (current boot), journalctl -k (kernel messages), journalctl -p err (priority filter).
Log analysis techniques: tail -f /var/log/syslog monitors in real-time, grep 'ERROR' /var/log/syslog finds errors, awk, sed for parsing structured logs, sort | uniq -c for frequency analysis. Example: grep 'Failed password' /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn lists failed login attempts by IP.
Common patterns: "Out of memory" indicates memory exhaustion, "Connection refused" suggests service not running or firewall blocking, "Permission denied" indicates file permission issues, "No space left on device" means disk full, "segmentation fault" indicates application crash. Correlate timestamps across logs to understand event sequences.
Log rotation: logrotate prevents logs from filling disk. Configuration in /etc/logrotate.conf and /etc/logrotate.d/. Settings: rotation frequency (daily, weekly), number of old logs to keep, compression, post-rotation scripts. Check logrotate status in /var/lib/logrotate/status.
Centralized logging: for multiple servers, use centralized logging (ELK stack, Splunk, Graylog) shipping logs to central server for analysis, correlation, and alerting. Understanding log analysis is fundamental for troubleshooting production issues.
252. Explain advanced cron usage including environment variables, output handling, error reporting, and alternatives like systemd timers.
Difficulty: HardType: SubjectiveTopic: Cron Jobs
Cron environment: limited PATH, HOME=/home/user, SHELL=/bin/sh by default. Set variables in crontab: PATH=/usr/local/bin:/usr/bin:/bin, MAILTO=admin@example.com, SHELL=/bin/bash. Variables before entries apply to all subsequent entries. Example:
```
PATH=/usr/local/bin:/bin:/usr/bin
MAILTO=admin@example.com
0 2 * * * /path/to/backup.sh
```
Output handling: cron emails stdout/stderr to MAILTO user (if mail configured). Redirect: 0 2 * * * /path/to/script.sh > /var/log/backup.log 2>&1 logs output. Suppress: 0 2 * * * /path/to/script.sh > /dev/null 2>&1 discards all output. Email only errors: 0 2 * * * /path/to/script.sh > /var/log/backup.log sends only stderr via email.
Error reporting: wrap scripts with error handling:
```bash
#!/bin/bash
set -e
trap 'echo "Backup failed" | mail -s "Backup Error" admin@example.com' ERR
# Backup commands
```
Or use cron wrapper: 0 2 * * * /usr/local/bin/cron-wrapper /path/to/script.sh where wrapper handles logging and error notification.
Locking: prevent overlapping executions:
```bash
0 */6 * * * flock -n /var/lock/backup.lock -c '/path/to/backup.sh'
```
Flock ensures only one instance runs. Alternative: check for PID file in script.
Systemd timers: modern alternative to cron. Create timer unit (/etc/systemd/system/backup.timer):
```
[Unit]
Description=Backup Timer
[Timer]
OnCalendar=daily
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
```
And service unit (backup.service). Enable: systemctl enable backup.timer, systemctl start backup.timer.
Advantages of timers: better logging with journalctl, dependency handling, RandomizedDelaySec for load distribution, OnBootSec for run-after-boot. List: systemctl list-timers. Disadvantages: more complex setup, systemd-specific.
At command: one-time scheduled tasks. at 10pm runs commands entered interactively. at 2:30 AM tomorrow < script.sh schedules script. List: atq, remove: atrm jobnumber. Understanding scheduling options enables reliable task automation.
253. How do you troubleshoot disk space and inode exhaustion issues? Explain finding large files, cleaning up space, and preventing future issues.
Difficulty: HardType: SubjectiveTopic: Disk Management
Identify disk space issues: df -h shows filesystem usage, alerts when >80-90% full. Find large files: du -sh /* | sort -h shows top-level directory sizes, du -ah /var | sort -h | tail -20 finds 20 largest files/dirs under /var. Recursive: find / -type f -size +100M lists files over 100MB, find / -type f -size +1G -exec ls -lh {} \; shows details.
Common space consumers: /var/log (old logs), /tmp (temporary files), /home (user files), /var/cache/apt or /var/cache/yum (package caches), Docker images (/var/lib/docker), database dumps. Clean: logrotate for logs, apt-get clean or yum clean all for package caches, docker system prune for Docker cleanup.
Inode exhaustion: df -i shows inode usage. Symptom: "No space left on device" despite df showing free space. Cause: millions of small files exhausting inodes. Find: find / -xdev -type f | cut -d / -f 2 | sort | uniq -c | sort -rn shows file count by top-level directory. Clean: remove unnecessary files, especially in /tmp, /var/spool.
Safe cleanup:
```bash
# Find old files
find /var/log -type f -mtime +30 -name "*.log"
# Archive before deleting
tar -czf old-logs-$(date +%Y%m%d).tar.gz $(find /var/log -type f -mtime +30 -name "*.log")
find /var/log -type f -mtime +30 -name "*.log" -delete
# Truncate instead of delete (preserves file handles)
> /var/log/large.log
```
Monitoring and alerts: set up monitoring (Nagios, Zabbix, Prometheus) alerting at 80% capacity. Automated cleanup: cron jobs deleting old files, log rotation, temporary file cleanup. Capacity planning: track growth trends, expand storage before reaching limits.
Quota management: set user quotas preventing individuals from filling disk. Enable: quotacheck, quotaon, edquota user sets limits. Useful in multi-user systems.
Prevention: proper log rotation, automated cleanup, user quotas, capacity monitoring, storage expansion planning. Understanding disk management prevents outages from full filesystems.
254. Explain Linux system performance tuning techniques. How do you identify bottlenecks and optimize CPU, memory, disk, and network performance?
Difficulty: HardType: SubjectiveTopic: System Monitoring
Identify bottlenecks: use monitoring tools determining if CPU, memory, disk I/O, or network is constraining performance. Top or htop shows CPU and memory, vmstat shows system stats, iostat shows disk I/O, sar provides historical data. High load average (>CPU cores) indicates CPU bottleneck, high swap usage indicates memory pressure, high iowait indicates disk bottleneck.
CPU optimization: identify CPU-intensive processes with top, nice/renice adjust process priority, taskset pins processes to specific CPU cores (CPU affinity), disable unnecessary services reducing CPU load, upgrade to more/faster CPUs. Tune: echo performance > /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor sets CPU governor to performance mode.
Memory optimization: add more RAM if constantly swapping, tune swappiness: echo 10 > /proc/sys/vm/swappiness reduces swap usage (default 60), tune cache pressure: echo 50 > /proc/sys/vm/vfs_cache_pressure controls caching behavior, identify memory leaks (growing RSS in top), disable unused services, use lightweight alternatives.
Disk I/O optimization: use faster storage (SSD instead of HDD), tune I/O scheduler: cat /sys/block/sda/queue/scheduler shows schedulers, echo deadline > /sys/block/sda/queue/scheduler sets deadline scheduler (good for SSDs), increase read-ahead: blockdev --setra 8192 /dev/sda, use separate disks for different workloads (logs on separate disk from database), tune filesystem mount options (noatime reduces writes), enable write caching (with UPS backup).
Network optimization: tune TCP buffers: sysctl -w net.core.rmem_max=16777216, sysctl -w net.core.wmem_max=16777216 increases buffer sizes, tune TCP settings: sysctl -w net.ipv4.tcp_tw_reuse=1 allows reusing TIME_WAIT connections, use faster network interface, enable jumbo frames on gigabit networks: ifconfig eth0 mtu 9000.
Filesystem tuning: choose appropriate filesystem (XFS for large files, ext4 for general use), tune mount options (noatime, nodiratime, data=writeback for performance, data=journal for consistency), adjust reserved blocks: tune2fs -m 1 /dev/sda1 reduces reserved space from 5% to 1%.
Kernel tuning: parameters in /etc/sysctl.conf or /proc/sys. Examples: net.ipv4.ip_local_port_range for port range, net.core.somaxconn for connection queue, vm.dirty_ratio and vm.dirty_background_ratio for write caching. Apply: sysctl -p.
Benchmarking: establish baseline before tuning, benchmark after changes, common tools: sysbench (CPU, memory, I/O), iperf (network), fio (disk I/O), stress-ng (stress testing). Document changes and results. Understanding performance tuning optimizes system resource utilization.
255. Explain comprehensive backup and disaster recovery strategies for Linux systems. Discuss backup types, automation, testing, and recovery procedures.
Difficulty: HardType: SubjectiveTopic: Backup Restore
Backup types: Full backup copies all data (complete snapshot, large, slow), Incremental backup copies changes since last backup (faster, requires all previous backups for restore), Differential backup copies changes since last full backup (faster than full, easier restore than incremental), Snapshot/delta backup copies only changed blocks (efficient, requires special tools like rsnapshot, borgbackup).
Backup strategy: 3-2-1 rule - 3 copies (original + 2 backups), 2 different media types (disk + tape/cloud), 1 offsite (protection against site disasters). RPO (Recovery Point Objective) - acceptable data loss timeframe, RTO (Recovery Time Objective) - acceptable downtime for restoration.
Tools and methods:
```bash
# Tar backup
tar -czf backup-$(date +%Y%m%d).tar.gz /data --exclude='*.tmp'
# Rsync incremental backup
rsync -av --delete /data/ /backup/latest/
# Rsnapshot (hard-link based, space-efficient)
rsnapshot daily
# Borgbackup (deduplication, compression, encryption)
borg create /backup/repo::$(date +%Y%m%d) /data
# Database backup
mysqldump -u root -p --all-databases | gzip > db-backup-$(date +%Y%m%d).sql.gz
```
Automation: cron jobs for scheduled backups:
```bash
# /etc/cron.d/backup
0 2 * * * root /usr/local/bin/backup.sh 2>&1 | logger -t backup
0 3 * * 0 root /usr/local/bin/full-backup.sh 2>&1 | logger -t backup
```
Include error handling, notifications, logging. Lock files prevent overlapping backups.
What to backup: configuration files (/etc), user data (/home), application data (/var/www, /var/lib), databases, log files (for forensics), system state (package list: dpkg --get-selections > packages.txt).
Testing backups: regularly test restoration process (monthly), automate test restores to separate system, document recovery procedures, verify backup integrity (checksums, test files), test offsite retrieval.
Recovery procedures:
```bash
# File restore from tar
tar -xzf backup.tar.gz -C / path/to/file
# Rsync restore
rsync -av /backup/latest/ /data/
# Borg restore
borg extract /backup/repo::20240115 path/to/restore
# Database restore
zcat db-backup.sql.gz | mysql -u root -p
```
Disaster recovery: document DR plan, maintain recovery media (bootable USB with tools), store offsite backup credentials securely, practice full system rebuild, automate infrastructure with config management (Ansible, Puppet) enabling quick rebuild, document dependencies and configurations.
Encryption: encrypt backups containing sensitive data: tar -czf - /data | gpg -c > backup.tar.gz.gpg, store encryption keys separately, test decryption regularly.
Retention policy: daily backups for 7 days, weekly for 4 weeks, monthly for 12 months, yearly for long-term archival. Balance storage cost vs. recovery requirements. Understanding backup strategies prevents data loss and minimizes recovery time.
256. What are essential Linux security hardening practices? Discuss SSH security, firewall configuration, SELinux/AppArmor, and security updates.
Difficulty: HardType: SubjectiveTopic: Security Hardening
SSH hardening (/etc/ssh/sshd_config): disable root login (PermitRootLogin no), use key-based authentication only (PasswordAuthentication no, PubkeyAuthentication yes), change default port (Port 2222), limit users (AllowUsers user1 user2), use Protocol 2 only, set LoginGraceTime 30, MaxAuthTries 3, disable empty passwords (PermitEmptyPasswords no), disable X11 forwarding if not needed (X11Forwarding no).
Firewall configuration: enable firewall (ufw, firewalld, iptables), default deny policy, whitelist necessary ports only. UFW: ufw default deny incoming, ufw allow 22/tcp, ufw allow 80/tcp, ufw enable. Iptables: iptables -P INPUT DROP, iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT, iptables -A INPUT -p tcp --dport 22 -j ACCEPT, persist with iptables-save.
Minimize attack surface: disable unused services (systemctl disable service), remove unnecessary packages (apt remove or yum remove), close unnecessary ports, run services as non-root users, use chroot jails or containers for service isolation.
SELinux/AppArmor: mandatory access control systems. SELinux (RHEL/CentOS): enforce policies restricting process actions, set to enforcing mode: setenforce 1, check status: getenforce, fix context: restorecon -Rv /path, audit logs in /var/log/audit/audit.log. AppArmor (Ubuntu): profile-based confinement, enable profile: aa-enforce /etc/apparmor.d/usr.bin.program, check status: aa-status.
Security updates: enable automatic security updates (unattended-upgrades on Debian/Ubuntu, yum-cron on RHEL/CentOS), configure notification, test in staging before production, subscribe to security mailing lists (ubuntu-security-announce, centos-announce), monitor CVEs for installed software.
Password policies: enforce strong passwords with PAM (pam_pwquality), set password expiration (chage -M 90 user), lock accounts after failed attempts (pam_faillock), audit passwords with john the ripper (authorized testing).
File permissions: review world-writable files: find / -xdev -type f -perm -002, review setuid files: find / -xdev -type f -perm -4000 (potential security risks), protect sensitive files (600 for SSH keys, 640 for config files), audit with aide or tripwire detecting unauthorized changes.
Audit logging: enable auditd for system call auditing, log important events (file access, authentication, privilege escalation), central log collection, regular log review, configure retention policy.
Network security: disable IPv6 if not used, disable unnecessary network services, use TCP wrappers (/etc/hosts.allow, /etc/hosts.deny), configure reverse DNS, enable fail2ban for intrusion prevention (bans IPs with multiple failed logins).
Monitoring: install intrusion detection (OSSEC, Snort), monitor logs for suspicious activity, set up alerts for critical events, regular security scans (nmap for open ports, nikto for web vulnerabilities - authorized testing only), vulnerability scanning (OpenVAS, Nessus).
Understanding security hardening protects systems from attacks and ensures compliance with security standards.
257. Describe common Linux system issues and their troubleshooting approaches. Include boot failures, network problems, performance degradation, and service failures.
Difficulty: HardType: SubjectiveTopic: Service Management
Boot failures: symptoms - system won't start, kernel panic, drops to emergency shell. Troubleshooting: boot from live USB, check logs in /var/log, run fsck on filesystems, check /etc/fstab for errors (typos, wrong UUIDs), reinstall bootloader (grub-install), boot older kernel from GRUB menu, check hardware (bad RAM, failing disk with SMART data: smartctl -a /dev/sda).
Network problems: symptoms - no connectivity, slow network, DNS issues. Troubleshooting: ping 127.0.0.1 (test loopback), ping gateway (test local network), ping 8.8.8.8 (test internet without DNS), nslookup google.com (test DNS), check interface status: ip link, check IP configuration: ip addr, check routes: ip route, check DNS: cat /etc/resolv.conf, restart network: systemctl restart networking, check firewall rules, test with different DNS: nslookup google.com 8.8.8.8.
Performance degradation: symptoms - slow response, high load average, OOM killer activating. Troubleshooting: top/htop identify resource hogs, check CPU (>80% sustained), memory (high swap usage), disk I/O (high iowait in top), check for memory leaks (growing RSS), review logs for errors, analyze with sar historical data, investigate recent changes (new software, config changes, increased load), iostat for disk bottlenecks, netstat for network connections.
Service failures: symptoms - service won't start, keeps restarting, crashes. Troubleshooting: systemctl status service shows state and recent logs, journalctl -xu service shows detailed logs, check config files for syntax errors, verify file permissions, check dependencies: systemctl list-dependencies service, test manually: /usr/bin/service --verbose, review recent changes, check available resources (disk space, memory), strace for system call tracing.
Disk full issues: symptoms - "No space left" errors, applications crashing, can't write logs. Troubleshooting: df -h shows usage by filesystem, find large files: du -sh /* | sort -h, check inodes: df -i, clean /tmp and /var/tmp, rotate logs, clean package caches, find deleted but open files: lsof | grep deleted (restart services to release), expand filesystem or add storage.
High CPU usage: identify process with top, check if legitimate load or bug (runaway loop), nice/renice to lower priority, kill if necessary, investigate application logs, check for infinite loops or inefficient queries, profile with strace or perf.
Memory issues: check with free -h, identify memory hogs with top (RSS column), check for leaks (memory growing over time), adjust swappiness if swapping too aggressively, add more RAM if consistently over capacity, check OOM killer logs: dmesg | grep -i kill.
Systematic approach: define problem clearly, collect information (logs, monitoring data, recent changes), form hypothesis, test hypothesis, implement fix, verify resolution, document solution. Understanding common issues and systematic troubleshooting reduces mean time to resolution.