⬡ Hub
Skip to content

Linux Interview Questions

Basic Level

1. What is the Linux kernel?

The Linux kernel is the core component of the Linux operating system. It acts as a bridge between the system's hardware and the software applications. The kernel is responsible for managing the system's resources, including the CPU, memory, and peripheral devices.

  • Use case: Every time you interact with your computer, the kernel is involved. For example, when you save a file, the kernel's filesystem driver handles writing the data to the disk. When you open an application, the kernel allocates memory for it and schedules it to run on the CPU.

2. What is a shell? What are some common shells?

A shell is a command-line interpreter that provides a user interface for accessing the services of the operating system. It's the primary way users interact with the kernel. You type commands into the shell, and it executes them.

  • Common Shells:

    • bash (Bourne Again SHell): The most widely used and the default shell for most Linux distributions.
    • sh (Bourne Shell): One of the first Unix shells, it's a predecessor to bash.
    • zsh (Z Shell): A powerful and highly customizable shell with features like advanced tab completion, spelling correction, and theming.
    • fish (Friendly Interactive SHell): A modern shell that focuses on user-friendliness with features like autosuggestions and syntax highlighting out of the box.
  • Code Example: You can find out which shell you are currently using with the following command: shell echo $SHELL

3. What is the difference between a command and a process?

3. What is the difference between a command and a process?

  • A command is an instruction given by a user to the computer. It's the name of a program you want to run (e.g., ls, grep, cp).
  • A process is an instance of a running program. When you execute a command, the operating system creates a process to run that program. Each process has its own memory space, resources, and a unique Process ID (PID).

Analogy: Recipe vs. Cooking * A command is like a recipe in a cookbook. It's a static set of instructions. * A process is the act of cooking that recipe. You take the instructions (the command), use system resources like CPU and memory (ingredients and kitchen utensils), and you have an active, running instance of the recipe. You can even cook the same recipe multiple times simultaneously, creating multiple processes from the same command.

4. How do you list files in a directory?

The ls command is used to list files and directories.

  • Use cases and examples:
    • ls: Lists the files and directories in the current directory.
    • ls -l: Lists the files in a "long format," showing permissions, owner, group, size, and modification date.
    • ls -a: Lists all files, including hidden files (those that start with a .).
    • ls -lh: Lists files in a long format with human-readable file sizes (e.g., 1K, 23M, 5G).

5. How do you create a new directory?

The mkdir command is used to create a new directory.

  • Use case: To organize your files, you can create directories.
  • Code Example: shell mkdir my_new_directory You can also create nested directories with the -p option: shell mkdir -p project/src/components

6. How do you change your current directory?

The cd command is used to change the current working directory.

  • Use cases and examples:
    • cd /var/log: Change to the /var/log directory.
    • cd ..: Move up one level in the directory tree.
    • cd ~ or just cd: Change to your home directory.
    • cd -: Change to the previous directory you were in.

7. How do you view the contents of a file?

There are several commands for viewing file contents:

  • cat (concatenate): Reads a file and prints its entire content to the standard output.
    • Use case: Best for small files where you want to see the whole content at once.
    • Code Example: cat /etc/os-release
  • less: A pager that lets you view the content of a file one page at a time.
    • Use case: Ideal for large files. You can scroll up and down using the arrow keys.
    • Code Example: less /var/log/syslog
  • more: Similar to less, but with more limited functionality (e.g., you can't scroll backward).
  • head: Displays the first few lines of a file (10 by default).
    • Use case: To quickly see the beginning of a file.
    • Code Example: head -n 20 my_large_file.csv (shows the first 20 lines).
  • tail: Displays the last few lines of a file (10 by default).
    • Use case: Often used to view the most recent log entries. The -f option allows you to "follow" a file as it grows.
    • Code Example: tail -f /var/log/nginx/access.log

8. How do you create an empty file?

The touch command is the standard way to create an empty file.

  • Use case: To create a new file that you intend to edit later, or to update a file's modification timestamp.
  • Code Example: shell touch new_file.txt If new_file.txt already exists, this command will update its timestamp to the current time.

9. How do you copy a file?

The cp command is used to copy files and directories.

  • Use cases and examples:
    • cp source.txt destination.txt: Creates a copy of source.txt named destination.txt.
    • cp report.pdf /home/user/documents/: Copies report.pdf into the documents directory.
    • cp -r source_directory/ backup_directory/: Copies an entire directory and its contents recursively.

10. How do you move or rename a file?

The mv command is used to move or rename files and directories.

  • Use cases and examples:
    • Renaming: mv old_filename.txt new_filename.txt
    • Moving: mv my_file.txt /tmp/ (moves the file to the /tmp directory).

11. How do you delete a file?

The rm command is used to delete (remove) files.

  • Use cases and examples:
    • rm old_report.txt: Deletes the file old_report.txt.
    • rm -i sensitive_file.txt: The -i (interactive) flag prompts for confirmation before deleting.
    • To delete a directory and its contents, you must use the -r (recursive) option: rm -r old_project/
    • Warning: The rm command is permanent. Files deleted with rm are not moved to a "trash can." Use it with caution, especially with the -f (force) option, which will not prompt for confirmation.

12. What are file permissions in Linux?

File permissions control who can read, write, or execute a file. They are a fundamental part of Linux's security model, ensuring that users can only access the files and directories they are authorized to.

  • Permission Types:

    • Read (r): Allows viewing the contents of a file or listing the contents of a directory.
    • Write (w): Allows modifying a file or creating, deleting, and renaming files within a directory.
    • Execute (x): Allows running a file as a program or script, or entering (i.e., cd into) a directory.
  • User Types (The "Who"):

    • Owner (User): The single user who owns the file. By default, this is the user who created it.
    • Group: A collection of users who share a common set of permissions. This allows you to grant access to multiple users at once.
    • Others: Every other user on the system who is not the owner and not a member of the group.

    Analogy: A Shared Document (e.g., Google Docs) * Owner: You create a document. You are the owner and have full control. * Group: You share the document with "Edit" access with your immediate team. They are the group. * Others: You make the document public on the internet with "View only" access. This is what "others" represents.

  • Viewing Permissions: You can see the permissions of a file with ls -l. The first part of the output, like -rwxr-xr--, represents the permissions for the owner, group, and others, in that order.

13. How do you change file permissions?

The chmod command is used to change the permissions of a file or directory.

  • Symbolic Method (using letters):

    • chmod u+x my_script.sh: Adds execute permission for the user (owner).
    • chmod g-w config.txt: Removes write permission for the group.
    • chmod o=r public_info.txt: Sets the permissions for others to read-only.
    • chmod a+r data.csv: Adds read permission for all (user, group, and others).
  • Octal (Numeric) Method:

    • Permissions are represented by numbers: r=4, w=2, x=1.
    • You add the numbers for the permissions you want to grant for each user type (owner, group, others).
    • Example: chmod 755 my_script.sh
      • Owner: 7 (4+2+1) = rwx
      • Group: 5 (4+1) = r-x
      • Others: 5 (4+1) = r-x
      • This results in permissions of -rwxr-xr-x.

14. What are users and groups in Linux?

  • Users: An account that can log in and use the system. Each user has a unique User ID (UID) and a home directory.
  • Groups: A collection of users. Groups are a convenient way to manage permissions for multiple users at once. Each group has a unique Group ID (GID).

  • Use case: Imagine you have a team of developers working on a project. You can create a developers group and give that group write permissions to the project directory. By adding each developer's user account to the developers group, they all get the necessary access without having to manage permissions for each user individually.

15. How do you switch to another user?

The su (switch user) command is used to switch to another user account.

  • Use cases and examples:
    • su - username: Switches to the username account and loads their shell environment (as if they had logged in directly). You will be prompted for their password.
    • su: If run without a username, it attempts to switch to the root user.

16. What is the sudo command?

The sudo (superuser do) command allows a permitted user to execute a command as another user (usually the root user) without having to switch to that user's shell.

  • Use case: It is the preferred way to run commands with elevated privileges. Instead of logging in as root (which is generally discouraged for security reasons), you can use sudo for administrative tasks. This provides better security because it logs the command that was run, and you don't need to share the root password with multiple users.
  • Code Example: ```shell # Instead of this: # su - # apt-get update

    Do this:

    sudo apt-get update ```

17. How do you find help for a command?

There are several ways to get help for a command in Linux:

  • man <command>: The man (manual) command displays the manual page for a given command. This is the most comprehensive source of information.
    • Example: man ls
  • <command> --help: Most commands have a --help flag that prints a brief summary of their usage and options.
    • Example: grep --help
  • info <command>: The info command provides more detailed and structured information than man for some commands.

18. What is the purpose of the /etc directory?

The /etc directory is one of the most important directories in Linux. It contains system-wide configuration files for the operating system and various installed applications.

  • Use case: When you want to change the configuration of the SSH server, you would edit the /etc/ssh/sshd_config file. The user database is stored in /etc/passwd.
  • Examples of files in /etc:
    • /etc/passwd: User account information.
    • /etc/fstab: Filesystem table, which defines how disk partitions are mounted.
    • /etc/hostname: The system's hostname.
    • /etc/resolv.conf: DNS resolver configuration.

19. What is the purpose of the /var directory?

The /var directory contains variable data files. The contents of this directory are expected to grow and change as the system is used.

  • Use case: This is where you would look for log files to troubleshoot a problem, or where a web server would store its website files.
  • Examples of directories in /var:
    • /var/log: System and application log files.
    • /var/www: Web server content.
    • /var/tmp: Temporary files that should be preserved between reboots.
    • /var/spool/mail: User mailboxes.

20. What is the purpose of the /home directory?

The /home directory contains the personal home directories for each user on the system.

  • Use case: When a user jdoe logs in, their home directory is /home/jdoe. This is where they store their personal files, documents, and user-specific configuration files (e.g., .bashrc, .profile).

Intermediate Level

1. What is the difference between a hard link and a soft link?

  • Hard Link:

    • A hard link is a direct reference to an inode (a data structure that stores information about a file).
    • It's like having two different filenames pointing to the same file content.
    • You can't create a hard link for a directory.
    • Hard links cannot span across different filesystems.
    • If you delete the original file, the hard link will still work because the inode and the data are not removed until all hard links to it are removed.
    • Code Example: ln original_file.txt hard_link.txt
  • Soft Link (Symbolic Link):

    • A soft link (or symlink) is a special type of file that points to another file or directory by name (like a shortcut in Windows).
    • It does not point directly to the inode.
    • You can create a soft link for a directory.
    • Soft links can span across different filesystems.
    • If you delete the original file, the soft link will be "broken" and will not work.
    • Code Example: ln -s original_file.txt soft_link.txt

2. What are inodes?

An inode (index node) is a data structure on a filesystem that stores all the information about a file or directory, except for its name and its actual data. This information includes:

  • File type (e.g., regular file, directory, symbolic link).
  • Permissions (read, write, execute).
  • Owner and group.
  • File size.
  • Timestamps (creation, modification, last access).
  • Pointers to the disk blocks where the file's data is stored.

You can view the inode number of a file using the -i option with ls: ls -i myfile.txt

3. Explain the Linux boot process.

The Linux boot process is the sequence of stages that the system goes through from the moment it is powered on until it is ready for a user to log in. While it can vary slightly between systems, the general process is as follows:

  1. BIOS/UEFI Firmware: When you power on the system, the Basic Input/Output System (BIOS) or the more modern Unified Extensible Firmware Interface (UEFI) is the first software to run. It performs a POST (Power-On Self-Test) to initialize and check the system's hardware (like CPU, memory, and disks). The firmware then searches for a bootable device (like a hard drive or SSD) based on a pre-configured boot order.

  2. Bootloader (GRUB/LILO): The firmware loads the first sector of the bootable device, which contains the first stage of the bootloader (e.g., GRUB2). The bootloader's job is to load the Linux kernel into memory. It may present a menu allowing you to select which kernel to boot, especially if you have multiple kernels installed. The bootloader also loads the initramfs file into memory.

  3. Kernel Initialization: The kernel is now loaded into memory and takes control. It decompresses itself and mounts the initramfs (initial RAM filesystem). This is a temporary, in-memory root filesystem that contains the necessary drivers and tools (e.g., for storage controllers) that the kernel needs to mount the real root filesystem.

  4. Mounting the Root Filesystem: The kernel uses the drivers from the initramfs to mount the actual root filesystem (the one on your hard drive, defined in /etc/fstab) in a read-only mode.

  5. init Process (PID 1): Once the root filesystem is mounted, the kernel starts the very first user-space process, /sbin/init, which always has a Process ID (PID) of 1. This init process is the ancestor of all other processes on the system. On modern systems, /sbin/init is typically a symbolic link to systemd.

  6. Runlevels/Targets: The init/systemd process reads its configuration and brings the system to the state defined by the default target (for systemd) or runlevel (for older SysVinit systems). It starts various system services and daemons, mounts filesystems listed in /etc/fstab, and brings up network interfaces.

  7. Login: Finally, once all services for the target/runlevel are started, the system presents a login prompt, either on a text console or a graphical display manager, ready for the user to log in.

Simplified Flow Diagram:

+----------------+
|   Power On     |
+----------------+
        |
        v
+----------------+
|   BIOS/UEFI    | (Hardware Initialization, POST)
+----------------+
        |
        v
+----------------+
| Bootloader(GRUB)| (Loads Kernel & initramfs)
+----------------+
        |
        v
+----------------+
|     Kernel     | (Mounts initramfs, then real root fs)
+----------------+
        |
        v
+----------------+
| Init/Systemd(PID 1)| (Starts system services)
+----------------+
        |
        v
+----------------+
| Target/Runlevel| (e.g., multi-user, graphical)
+----------------+
        |
        v
+----------------+
|  Login Prompt  |
+----------------+

4. What is a process ID (PID) and a parent process ID (PPID)?

  • PID (Process ID): A unique identification number that is assigned to each running process in an operating system.
  • PPID (Parent Process ID): The PID of the process that created the current process.

Every process in Linux has a parent, except for the init process (PID 1), which is the ancestor of all other processes. You can see the PID and PPID of processes using the ps command: ps -ef

5. How do you find the PID of a process?

There are several ways to find the PID of a process:

  • pgrep <process_name>: This is the easiest way. It searches for processes by name and prints their PIDs.
    • Example: pgrep sshd
  • ps aux | grep <process_name>: This is a classic combination. ps aux lists all running processes, and grep filters the output to find the process you're looking for.
    • Example: ps aux | grep nginx

6. How do you send signals to a process (e.g., kill, killall)?

Signals are a fundamental form of inter-process communication in Unix-like systems. They are used to notify a process of an event. The kill and killall commands are the primary tools for sending these signals.

  • kill <PID>: Sends a signal to a specific Process ID.
  • killall <process_name>: Sends a signal to all processes matching the given name.

While there are many signals (you can see them all with kill -l), a few are used very frequently:

  • 1) SIGHUP (Hangup):

    • Purpose: Historically used to signal a user had "hung up" (disconnected their terminal). Today, it's commonly used to tell a service to reload its configuration file without shutting down.
    • Example: sudo kill -HUP 1234 or sudo kill -1 1234. Many services like Apache and Nginx will reload their configs upon receiving SIGHUP.
  • 2) SIGINT (Interrupt):

    • Purpose: This is the signal sent when you press Ctrl+C in the terminal. It's an interrupt request sent to the foreground process.
    • Example: Running a script and pressing Ctrl+C sends SIGINT to stop it.
  • 15) SIGTERM (Terminate):

    • Purpose: This is the default and preferred signal for terminating a process. It's a polite request asking the process to shut down gracefully. The application can "catch" this signal to perform cleanup operations (like saving files or closing network connections) before exiting.
    • Example: kill 1234 is the same as kill -TERM 1234.
  • 9) SIGKILL (Kill):

    • Purpose: This is the "ultimate weapon." It's a forceful and immediate termination of the process. The process cannot catch, block, or ignore this signal.
    • Use Case: Use this as a last resort when a process is unresponsive and has ignored a SIGTERM. Because it's immediate, the process has no chance to clean up after itself.
    • Example: kill -9 1234.
  • 19) SIGSTOP & 18) SIGCONT (Stop & Continue):

    • Purpose: SIGSTOP pauses a process without terminating it. SIGCONT resumes a paused process. This is what happens when you use Ctrl+Z in the shell and then resume the job with the fg command.
    • Example: kill -STOP 1234 to pause, kill -CONT 1234 to resume.

7. What is the difference between kill and kill -9?

  • kill <PID> (or kill -15 <PID>): Sends the TERM (terminate) signal. This is a polite request for the process to shut down. The process can catch this signal and perform cleanup operations before exiting.
  • kill -9 <PID>: Sends the KILL signal. This is a forceful and immediate termination of the process. The process cannot catch or ignore this signal. It's a last resort when a process is unresponsive.

8. How do you view running processes?

  • ps: The ps (process status) command provides a snapshot of the currently running processes.
    • ps aux: Shows all processes for all users in a detailed format.
    • ps -ef: Shows all processes in a full format, including the command line.
  • top: The top command provides a real-time, dynamic view of the running processes. It's great for seeing which processes are consuming the most CPU and memory.
  • htop: An improved version of top with a more user-friendly interface, color, and the ability to scroll and manage processes easily.

9. What is the ps command and what are some common options?

The ps command reports a snapshot of the current processes.

  • Common Options:
    • a: Show processes for all users.
    • u: Display user-oriented format.
    • x: Show processes not attached to a terminal.
    • e: Display all processes.
    • f: Display a "forest" of processes, showing parent-child relationships.
    • Common Combination: ps aux or ps -ef

10. What is the top command and what information does it show?

The top command provides a real-time view of the system's performance and the processes running on it. It shows:

  • System uptime, number of users, and load average.
  • Number of tasks (processes) and their states (running, sleeping, etc.).
  • CPU usage (user, system, idle).
  • Memory usage (total, used, free).
  • A list of running processes, with information like PID, user, CPU usage, memory usage, and the command.

11. What is I/O redirection? Give examples of input, output, and error redirection.

I/O redirection allows you to change where a command's input comes from and where its output and errors go.

  • Standard Input (stdin, file descriptor 0):
    • command < input_file: The command reads its input from input_file instead of the keyboard.
    • Example: sort < names.txt
  • Standard Output (stdout, file descriptor 1):
    • command > output_file: The command's output is written to output_file instead of the screen (overwrites the file).
    • command >> output_file: Appends the output to output_file.
    • Example: ls -l > file_list.txt
  • Standard Error (stderr, file descriptor 2):
    • command 2> error_log: The command's error messages are written to error_log.
    • Example: find / -name "myfile" 2> /dev/null (redirects errors to /dev/null to discard them).
    • command > output.txt 2>&1: Redirects both stdout and stderr to the same file.

12. What are pipes (|) in Linux? Give an example.

A pipe is a form of redirection that is used to send the standard output of one command to the standard input of another command. This allows you to chain commands together to perform complex tasks.

  • Example: shell ps aux | grep "nginx" | wc -l
    1. ps aux: Lists all running processes.
    2. |: The pipe sends the output of ps aux to the grep command.
    3. grep "nginx": Filters the input and only shows lines containing "nginx".
    4. |: The pipe sends the output of grep to the wc command.
    5. wc -l: Counts the number of lines, effectively counting the number of nginx processes.

13. What is the grep command and how is it used?

The grep (Global Regular Expression Print) command is a powerful command-line utility used to search for a specific pattern of text within files or from standard input. It prints any lines that contain a match for the pattern.

  • Common Options and Use Cases:

    • grep "error" /var/log/syslog: Searches for the literal string "error" in the system log.
    • grep -i "user" /etc/passwd: Performs a case-insensitive search.
    • grep -r "API_KEY" /etc/: Recursively searches for "API_KEY" in all files under the /etc/ directory.
    • grep -v "success" results.txt: Inverts the match, showing all lines that do not contain "success".
    • ps aux | grep "sshd": Pipes the output of ps to grep to find the sshd process.
  • Advanced Use Case: Searching with Regular Expressions grep's true power comes from its support for regular expressions, allowing you to search for patterns, not just fixed strings.

    • Scenario: You want to find all unique IP addresses that have accessed your web server from an Nginx access log.
    • Code Example: shell grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /var/log/nginx/access.log | sort | uniq -c
      • grep -E: Uses Extended Regular Expression syntax, which makes the pattern easier to read.
      • -o: Prints only the matching part of the line (in this case, just the IP address), not the entire log line.
      • '[0-9]{1,3}\.'...: This is the regular expression that matches the pattern of an IP address.
      • | sort | uniq -c: The output is then piped to sort the IPs, and then to uniq -c to count the occurrences of each unique IP.

14. What is the find command and how is it used?

The find command is used to search for files and directories in a directory hierarchy based on various criteria.

  • Use cases and examples:
    • find /home -name "*.txt": Find all files with the .txt extension in the /home directory.
    • find / -type d -name "config": Find all directories named "config" starting from the root directory.
    • find . -mtime -7: Find all files in the current directory that have been modified in the last 7 days.
    • find /tmp -name "*.log" -delete: Find and delete all .log files in /tmp.

15. What is the sed command and how is it used?

The sed (stream editor) command is a powerful tool for parsing and transforming text. It can perform operations like search and replace on a file or a stream of data.

  • Use case: Often used for find-and-replace operations in scripts.
  • Code Example: shell sed 's/old_text/new_text/g' input.txt > output.txt This command replaces all occurrences (g) of "old_text" with "new_text" in input.txt and writes the result to output.txt.

16. What is the awk command and how is it used?

awk is a versatile programming language designed for text processing. It's particularly good at processing files that are organized into columns.

  • Use case: Extracting specific columns of data from a text file.
  • Code Example: shell ls -l | awk '{print $1, $9}' This command takes the output of ls -l and prints the first ($1, permissions) and ninth ($9, filename) columns.

17. What are environment variables? How do you set and view them?

Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer.

  • Viewing Variables:
    • env or printenv: Display all environment variables.
    • echo $VAR_NAME: Display the value of a specific variable (e.g., echo $HOME).
  • Setting Variables:
    • export VAR_NAME="value": Sets an environment variable for the current shell session and any child processes.
    • To make a variable permanent, you need to add the export command to your shell's startup file (e.g., ~/.bashrc or ~/.zshrc).

18. What is the PATH environment variable?

The PATH environment variable is a list of directories that the shell searches for executable files when you type a command.

  • Use case: When you type the ls command, the shell looks for an executable file named ls in the directories listed in the PATH variable (e.g., /bin, /usr/bin).
  • You can view your PATH with echo $PATH.

19. What is a cron job? How do you schedule one?

A cron job is a time-based job scheduler in Unix-like operating systems. It allows you to schedule commands or scripts to run automatically at a specific time or interval.

  • Scheduling a Cron Job:
    • You edit the crontab file using the command crontab -e.
    • Each line in the crontab file represents a job and has the following format: ```
              • /path/to/command | | | | | | | | | +----- Day of the week (0 - 7) (Sunday is 0 or 7) | | | +------- Month (1 - 12) | | +--------- Day of the month (1 - 31) | +----------- Hour (0 - 23) +------------- Minute (0 - 59) ```
    • Example: To run a backup script every day at 2 AM: 0 2 * * * /home/user/scripts/backup.sh

20. How do you manage services in Linux (e.g., using systemctl)?

On modern Linux distributions that use systemd, the systemctl command is the primary tool for managing services.

  • Common systemctl Commands:
    • systemctl start <service>: Start a service.
    • systemctl stop <service>: Stop a service.
    • systemctl restart <service>: Restart a service.
    • systemctl status <service>: Check the status of a service.
    • systemctl enable <service>: Enable a service to start automatically on boot.
    • systemctl disable <service>: Disable a service from starting on boot.
  • Example: To restart the SSH server: shell sudo systemctl restart sshd

Expert Level

... (existing expert questions) ...

20. What is RAID? What are the different RAID levels?

RAID (Redundant Array of Independent Disks) is a technology that combines multiple physical disk drives into a single logical unit for the purposes of data redundancy, performance improvement, or both.

  • Common RAID Levels:
    • RAID 0 (Striping): Data is split across multiple disks. High performance, but no redundancy.
    • RAID 1 (Mirroring): Data is written to two disks simultaneously. Provides redundancy.
    • RAID 5 (Striping with Parity): Data is striped across multiple disks, and parity information is also striped across the disks. Provides a good balance of performance and redundancy.
    • RAID 6 (Striping with Double Parity): Similar to RAID 5, but with two parity blocks. Can withstand the failure of two disks.
    • RAID 10 (1+0): A combination of mirroring and striping. Provides high performance and redundancy.

Core System Administration Tasks

21. How do you manage file permissions and ownership? Explain chmod and chown with examples.

Answer:

Managing file permissions and ownership is a fundamental security task in Linux. This is done using the chmod (change mode) and chown (change owner) commands.

Understanding Permissions (ls -l)

When you run ls -l, you see output like -rwxr-x---. * The first character (-) indicates the file type (d for directory, l for link). * The next 9 characters are three sets of permissions for User (owner), Group, and Other. * r = read, w = write, x = execute.

chown (Change Owner)

The chown command changes the user and/or group ownership of a file or directory.

  • Syntax: chown [user]:[group] [file/directory]
  • Examples:
    • Change the owner of a file to jdoe: shell sudo chown jdoe /var/www/index.html
    • Change the owner and group of a file: shell sudo chown jdoe:www-data /var/www/index.html
    • Change the group only (note the leading colon): shell sudo chown :www-data /var/www/index.html
    • Change ownership of a directory and all its contents recursively (-R): shell sudo chown -R jdoe:developers /opt/app

chmod (Change Mode)

The chmod command changes the permissions of a file or directory. It can be used in two modes: symbolic and octal.

  • Symbolic Mode (ugoa, +-=, rwx): Easier to understand for simple changes.

    • u (user), g (group), o (other), a (all)
    • + (add), - (remove), = (set exactly)
    • r (read), w (write), x (execute)
    • Examples:
      • Add execute permission for the user (owner): chmod u+x my_script.sh
      • Remove write permission for the group: chmod g-w config.yml
      • Give the owner read/write, and the group/others read-only: chmod u=rw,go=r data.csv
      • Recursively add write permission for the group on a directory: chmod -R g+w /srv/shared
  • Octal (Numeric) Mode: Faster for setting all permissions at once.

    • r = 4, w = 2, x = 1
    • You sum the numbers for each of the three entities (User, Group, Other).
    • Common Examples:
      • chmod 755 my_script.sh: -rwxr-xr-x (Owner can rwx, group/other can r-x). Common for executable scripts.
      • chmod 644 index.html: -rw-r--r-- (Owner can rw, group/other can r). Common for web files.
      • chmod 600 id_rsa: -rw------- (Owner can rw, nobody else has any permissions). Required for SSH private keys.
      • chmod 777 /tmp/shared: drwxrwxrwx (Everyone can do everything). Use with caution.

22. How do you find and manage running processes? Explain ps, top, kill, and nice.

Answer:

Process management is a key administrative task for monitoring system health and stopping misbehaving applications.

  • ps (Process Status): Provides a snapshot of running processes.

    • Use Case: To see what's running at a specific moment.
    • Examples:
      • ps aux: The most common usage. Shows all processes, in user-oriented format, including processes not attached to a texrminal.
      • ps -ef: Similar to ps aux, but shows a full listing in a standard format. Often used to see parent-child relationships.
      • To find a specific process, pipe the output to grep: shell ps aux | grep "nginx"
  • top / htop: Provide a real-time, interactive view of running processes.

    • Use Case: To see which processes are consuming the most CPU and memory right now.
    • top is the classic tool. htop is a popular, more user-friendly alternative with color, scrolling, and easier process management.
    • Inside top or htop, you can sort by CPU (P), memory (M), and send signals to processes.
  • kill: Sends a signal to a process to terminate it.

    • Use Case: To stop a running process.
    • Examples:
      • First, find the Process ID (PID) using ps or pgrep: pgrep my-app
      • Polite Kill (SIGTERM): Asks the process to shut down gracefully. This is the default and preferred method. shell kill 12345
      • Forceful Kill (SIGKILL): Forcibly terminates the process immediately. The process has no chance to clean up. Use this as a last resort for unresponsive processes. shell kill -9 12345
  • nice / renice: Adjusts the scheduling priority of a process.

    • Use Case: To make a long-running, non-critical process use less CPU, or to give a critical process more CPU time.
    • The "niceness" value ranges from -20 (highest priority) to 19 (lowest priority).
    • Examples:
      • Start a process with a lower priority: shell nice -n 10 ./my-long-script.sh
      • Change the priority of a running process (requires PID): shell renice 15 12345

23. What are some common commands for troubleshooting network issues?

Answer:

When troubleshooting network issues, you need a set of tools to test connectivity, check open ports, and inspect network configuration.

  • ping: Tests basic connectivity to another host.

    • Use Case: The first command to run to see if a remote host is reachable.
    • Example: It sends ICMP echo requests and waits for replies. shell ping google.com
  • ip: The modern, all-in-one tool for managing network interfaces and routing tables.

    • Use Case: To check your system's IP address, interface status, and routing rules.
    • Examples:
      • Show IP addresses and interfaces: ip addr show (or ip a)
      • Show the routing table: ip route show (or ip r)
  • ss / netstat: Shows active network connections and listening ports.

    • Use Case: To check what services are listening on your server or to inspect active connections. ss is the modern replacement for the older netstat.
    • Examples:
      • Show all listening TCP and UDP ports, the process using them, and don't resolve hostnames (-tulpn is a very common combination). shell sudo ss -tulpn # -t: TCP, -u: UDP, -l: listening, -p: process, -n: numeric
  • dig / nslookup: Used to query DNS servers.

    • Use Case: To check if a domain name is resolving to the correct IP address. dig is generally preferred as it provides more detailed information.
    • Example: shell dig api.example.com
  • traceroute / mtr: Shows the path (the sequence of routers) that packets take to reach a destination.

    • Use Case: To identify where a network connection is failing along its path. mtr combines ping and traceroute into a single, real-time diagnostic tool.
    • Example: shell traceroute google.com

24. How do you effectively search and monitor log files?

Answer:

Searching and monitoring logs is essential for troubleshooting applications and system issues. The primary tools for this are grep, tail, and journalctl.

  • grep (Global Regular Expression Print): Searches for patterns in text.

    • Use Case: To find specific error messages or events within large log files.
    • Examples:
      • Search for "error" in a log file: shell grep "error" /var/log/nginx/error.log
      • Case-insensitive search and show 5 lines of context before and after the match (-i, -C): shell grep -i -C 5 "failed login" /var/log/auth.log
  • tail: Outputs the last part of files.

    • Use Case: Its most important feature is -f (follow), which allows you to monitor a log file in real-time as new entries are added.
    • Example: shell tail -f /var/log/syslog This command will display new log entries as they are written to syslog. You can exit by pressing Ctrl+C.
  • journalctl: The command-line tool for querying logs from the systemd journal.

    • Use Case: The modern, standard way to view logs on most Linux distributions for system services.
    • Examples:
      • View all logs for a specific service (e.g., sshd): shell sudo journalctl -u sshd.service
      • Follow the logs for a specific service in real-time: shell sudo journalctl -u sshd.service -f
      • Show logs from the last hour: shell sudo journalctl --since "1 hour ago"

Combining Tools: You can also pipe the output of journalctl to grep for more specific filtering.

sudo journalctl -u nginx.service | grep "denied"

25. How do you check disk usage on a Linux system? Explain df and du.

Answer:

Checking disk usage is a common task to prevent filesystems from filling up. The two primary commands for this are df (disk free) and du (disk usage).

  • df (Disk Free): Reports filesystem disk space usage.

    • Use Case: To get a high-level overview of how much space is used and available on all mounted filesystems.
    • Key Option: -h (human-readable), which prints sizes in powers of 1024 (e.g., 1K, 234M, 2G).
    • Example: shell df -h Output might look like: Filesystem Size Used Avail Use% Mounted on /dev/sda1 50G 20G 30G 40% / /dev/sdb1 200G 150G 50G 75% /data
  • du (Disk Usage): Estimates file and directory space usage.

    • Use Case: To find out which specific files and directories are consuming the most space within a particular location.
    • Key Options:
      • -h (human-readable).
      • -s (summarize), which displays only a total for each argument.
      • -d (depth), to specify how many levels of directories to show.
    • Examples:
      • Show a summary of the current directory's total size: shell du -sh .
      • Show the size of each directory in the current location (depth 1): shell du -h -d 1
      • Combine with sort to find the top 10 largest directories in /var/log: shell sudo du -h /var/log | sort -rh | head -n 10

Summary: * Use df to see how much free space you have on your partitions. * Use du to see what is using up the space within a directory.

Troubleshooting Questions

1. A user complains they cannot access a file. What steps would you take to troubleshoot this?

  1. Check File Permissions: Use ls -l /path/to/file to check the file's permissions. Ensure that the user has the necessary read (and execute, for directories) permissions.
  2. Check Directory Permissions: Check the permissions of the parent directories. A user needs execute (x) permission on all parent directories to be able to access a file within them.
  3. Check File Ownership: Use ls -l to see the owner and group of the file. Is the user the owner or a member of the group?
  4. Check for ACLs: Use getfacl /path/to/file to see if any Access Control Lists (ACLs) are in place that might be denying access.
  5. Check for SELinux/AppArmor: If SELinux or AppArmor is in enforcing mode, it might be blocking access. Check the audit logs (/var/log/audit/audit.log for SELinux, or dmesg for AppArmor) for any denial messages.

2. A service (e.g., a web server) is not running. How would you troubleshoot this?

This is a very common scenario for system administrators. Here's a systematic approach to debug why a service isn't starting or is failing:

  1. Check Service Status (systemctl status):

    • Action: The absolute first step is to check the service's current state.
    • Command: sudo systemctl status <service_name>.service (e.g., sudo systemctl status nginx.service)
    • Look for:
      • Is it active (running) or inactive (dead)?
      • If it failed, what is the specific error message or exit code?
      • The last few lines of its log output. This often provides immediate clues.
  2. Inspect Service Logs (journalctl -u):

    • Action: If systemctl status provides general information or refers to logs, dive deeper into the systemd journal.
    • Command: sudo journalctl -u <service_name>.service --no-pager (add -f to follow in real-time)
    • Look for: Specific error messages, warnings, or stack traces that indicate the root cause. Pay attention to timestamps.
  3. Verify Configuration Files:

    • Action: Many services fail to start due to misconfigured files.
    • Common Locations: Configuration files are usually in /etc/<service_name>/ (e.g., /etc/nginx/nginx.conf).
    • Check:
      • Syntax: Does the service have a command to test its configuration? (e.g., sudo nginx -t for Nginx, apachectl configtest for Apache).
      • Permissions: Are the configuration files readable by the service user?
      • Paths: Are all paths referenced in the config correct and accessible?
  4. Check Port Availability (ss -tulpn):

    • Action: A service might fail to start because its required port is already in use by another process.
    • Command: sudo ss -tulpn | grep <port_number> (e.g., sudo ss -tulpn | grep 80)
    • Look for: If another process is listening on the service's port, identify and stop that process or reconfigure your service to use a different port.
  5. Examine System Resources:

    • Action: Services can fail due to lack of resources.
    • Check:
      • Disk Space: df -h to check for full filesystems (especially /var/log).
      • Memory: free -h or top/htop to see if the system is running out of RAM.
      • CPU: top/htop to see if the system is overloaded.
  6. Review Dependencies:

    • Action: Some services depend on others (e.g., a web application might depend on a database).
    • Check: Ensure all required dependencies are running and accessible. systemctl list-dependencies <service_name> can help identify them.
  7. Check SELinux/AppArmor (if enabled):

    • Action: Security frameworks can block legitimate service operations.
    • Check: Look for "denied" messages in audit.log (SELinux) or dmesg (AppArmor). Temporarily setting SELinux to permissive or disabling AppArmor for the service might confirm this as the cause (do not do this in production without careful consideration).

By following these steps, you can systematically narrow down the cause of a service failure and implement a solution.