Linux Interview Questions
35+ Linux interview questions organized by topic. Click "Show Answer" to reveal detailed answers. Covers commands, file system, permissions, processes, networking, shell scripting, and system administration.
Commands & Shell
Q: What is a pipe in Linux? Give a practical example.
A pipe (|) connects the standard output of one command to the standard input of another, allowing you to chain commands together. For example, ps aux | grep nginx | awk '{print $2}' lists all processes, filters for nginx, and extracts only the PIDs. Pipes create a pipeline where data flows left to right, and each command processes only what it receives from the previous one.
Q: What is the difference between >, >>, and 2>&1?
> redirects stdout to a file and overwrites it. >> appends stdout to the file without overwriting. 2>&1 redirects stderr (file descriptor 2) to wherever stdout (fd 1) is going. A common pattern is command > output.log 2>&1 which captures both normal output and errors into one file. You can also discard all output with command > /dev/null 2>&1.
Q: How do you find all .log files larger than 100MB modified in the last 7 days?
Use find / -name "*.log" -size +100M -mtime -7. The find command searches recursively from the given path. -name "*.log" matches the filename pattern, -size +100M filters for files larger than 100 megabytes, and -mtime -7 selects files modified within the last 7 days. You can add -exec ls -lh {} \; to see file details or -delete to remove them.
Q: What is the difference between grep, sed, and awk?
grep searches for patterns and filters lines that match (read-only). sed is a stream editor that transforms text in-place, commonly for find-and-replace (sed 's/old/new/g' file). awk is a full programming language for structured text processing, excelling at column-based data (awk '{print $1, $3}' file). In short: grep filters lines, sed edits text, awk processes fields.
Q: What is the difference between a hard link and a soft (symbolic) link?
A hard link (ln target link) is an additional directory entry pointing to the same inode as the original file. Deleting the original doesn't affect the hard link because both names share the same data blocks. A soft link (ln -s target link) is a separate file containing the path to the target. If the original is deleted, the soft link becomes a dangling link. Hard links cannot cross filesystems or link to directories; soft links can do both.
File System & Permissions
Q: Explain the Linux Filesystem Hierarchy Standard (FHS). What goes in /etc, /var, /opt, and /tmp?
The FHS defines the standard directory layout. /etc holds system configuration files (e.g., /etc/nginx/nginx.conf). /var stores variable data that changes during operation (logs in /var/log, databases, mail spools). /opt is for optional third-party software installed outside the package manager. /tmp holds temporary files that may be cleared on reboot. Other key directories: /home (user data), /usr (user programs and libraries), /bin and /sbin (essential binaries).
Q: What does chmod 755 mean? Break down the number.
Each digit represents permissions for owner, group, others respectively. Each digit is the sum of: 4 (read), 2 (write), 1 (execute). So 755 means: owner gets 7 (4+2+1 = rwx), group gets 5 (4+0+1 = r-x), others get 5 (4+0+1 = r-x). This is the standard permission for executable scripts and directories where the owner has full control and everyone else can read and execute but not modify.
Q: What is an inode? What happens when you run out of inodes?
An inode is a data structure that stores metadata about a file: permissions, ownership, timestamps, size, and pointers to data blocks on disk. Every file and directory has exactly one inode, identified by an inode number. If you run out of inodes (check with df -i), you cannot create new files even if disk space is available. This typically happens when millions of tiny files are created. Fix it by deleting unnecessary small files or reformatting the partition with more inodes.
Q: What is the sticky bit? Where is it commonly used?
The sticky bit (chmod +t or 1777) on a directory means only the file owner, directory owner, or root can delete or rename files within it, even if others have write permission. The classic example is /tmp which has permissions drwxrwxrwt — everyone can create files there, but you can only delete your own. Without the sticky bit, any user with write permission to the directory could delete anyone's files.
Q: What is the difference between chown and chmod? When would you use each?
chmod changes the permissions (read, write, execute) on a file or directory. chown changes the ownership (user and/or group). Use chmod when you need to control what actions are allowed (e.g., making a script executable with chmod +x script.sh). Use chown when you need to transfer ownership (e.g., chown www-data:www-data /var/www/html so the web server can access its files). Both support -R for recursive changes.
Process Management
Q: What is a PID? What is special about PID 1?
A PID (Process ID) is a unique integer the kernel assigns to each running process. PID 1 is the init process (typically systemd on modern systems) — the first user-space process started by the kernel at boot. It is the ancestor of all other processes and has a special role: it adopts orphaned processes and reaps zombie children. If PID 1 dies, the system panics. In Docker containers, PID 1 is whatever the ENTRYPOINT or CMD specifies.
Q: What is a zombie process? How do you identify and fix it?
A zombie process has finished executing but its parent has not called wait() to collect its exit status. It shows as state Z in ps aux and appears as <defunct>. Zombies use no CPU or memory — they are just entries in the process table. You cannot kill a zombie (it is already dead). The fix is to address the parent process: restart it, or send it SIGCHLD to prompt it to reap. If the parent itself dies, PID 1 (init) adopts and reaps the zombies automatically.
Q: Explain the fork() and exec() system calls. How does Linux create new processes?
Linux creates new processes in two steps. fork() creates a child process that is an exact copy of the parent (same code, data, file descriptors). The child gets a new PID. Then exec() replaces the child's memory with a new program. For example, when you type ls in bash: the shell calls fork() to create a copy of itself, then the child calls exec("/bin/ls") to become the ls program. The parent (bash) calls wait() until the child finishes.
Q: What is the difference between SIGTERM and SIGKILL? When should you use each?
SIGTERM (signal 15) is a graceful termination request — the process can catch it, clean up resources (flush buffers, close connections, release locks), and exit. SIGKILL (signal 9) is an immediate, forceful kill handled by the kernel — the process cannot catch, block, or ignore it. Always send SIGTERM first (kill PID) and wait 5-10 seconds. Only use SIGKILL (kill -9 PID) as a last resort, because it can leave corrupted files, unreleased locks, and orphaned child processes.
Q: What is the difference between a foreground and background process? How do you manage them?
A foreground process occupies the terminal — it receives keyboard input and blocks the shell until it finishes. A background process runs independently, freeing the terminal. Start a process in the background with & (e.g., ./backup.sh &). Suspend a foreground process with Ctrl+Z, then resume it in the background with bg or foreground with fg. Use jobs to list background jobs. For processes that must survive a logout, use nohup or tmux.
systemd & Services
Q: What is systemd and why did it replace SysVinit?
systemd is the init system and service manager on most modern Linux distributions (Ubuntu, CentOS, Debian, Fedora). It replaced SysVinit because it offers parallel service startup (faster boot), on-demand activation via socket/D-Bus/path, dependency-based ordering, cgroup-based process tracking (no orphaned daemons), and centralized logging via journald. SysVinit started services sequentially with shell scripts, making boot slow and service management fragile.
Q: What is the difference between systemctl start, systemctl enable, and systemctl enable --now?
systemctl start nginx starts the service immediately but it will not survive a reboot. systemctl enable nginx creates a symlink so the service starts automatically on boot but does not start it now. systemctl enable --now nginx does both: enables it for boot and starts it immediately. There is also systemctl disable (remove from boot) and systemctl mask (completely prevent starting, even manually).
Q: How do you view logs for a specific service? How do you filter by time or severity?
Use journalctl, the systemd journal viewer. journalctl -u nginx shows all logs for the nginx unit. Filter by time: journalctl -u nginx --since "1 hour ago" or --since "2026-04-01" --until "2026-04-02". Filter by severity: journalctl -u nginx -p err (shows error and above). Follow live: journalctl -u nginx -f. Check disk usage: journalctl --disk-usage. Rotate logs: journalctl --vacuum-size=500M.
Q: Describe the structure of a systemd unit file. What are the key sections?
A unit file has three main sections. [Unit] contains metadata: Description, After (ordering), Requires/Wants (dependencies). [Service] defines how the service runs: Type (simple, forking, oneshot), ExecStart (command to run), User, Restart (on-failure, always), RestartSec. [Install] defines boot behavior: WantedBy=multi-user.target means it starts in normal multi-user mode. Place custom unit files in /etc/systemd/system/ and run systemctl daemon-reload after changes.
Q: A service keeps failing after startup. How do you troubleshoot it?
Start with systemctl status myservice to see the active state, exit code, and recent log lines. Then check full logs with journalctl -u myservice -n 50 for detailed error messages. Common causes: wrong ExecStart path, missing permissions (User directive), port already in use, missing dependencies, or incorrect WorkingDirectory. Use systemctl cat myservice to inspect the unit file. After fixing, run systemctl daemon-reload then systemctl restart myservice.
Networking
Q: How do you check which ports are listening on a Linux server?
Use ss -tuln which shows TCP (-t) and UDP (-u) listening (-l) sockets with numeric ports (-n). This is the modern replacement for netstat. Add -p (ss -tulnp) to see which process owns each socket (requires root). For example, you might see *:80 owned by nginx and *:5432 owned by postgres. You can also use lsof -i :80 to find what is using a specific port.
Q: What is the difference between iptables and nftables? How do you block an IP address?
iptables is the traditional Linux firewall that uses chains (INPUT, OUTPUT, FORWARD) and rules to filter packets. nftables is its modern replacement with a cleaner syntax, better performance, and atomic rule updates. To block an IP with iptables: iptables -A INPUT -s 192.168.1.100 -j DROP. With nftables: nft add rule inet filter input ip saddr 192.168.1.100 drop. Many distributions provide frontends like ufw (Ubuntu) or firewalld (RHEL/CentOS) for simpler management.
Q: How does DNS resolution work on a Linux system?
When a program resolves a hostname, it follows this order: 1) Check /etc/hosts for a static mapping. 2) Query the DNS servers listed in /etc/resolv.conf (or managed by systemd-resolved). The order is configured in /etc/nsswitch.conf under the hosts: line (typically files dns). Use dig example.com or nslookup example.com to test DNS resolution. Use getent hosts example.com to test the full resolution chain including /etc/hosts.
Q: How do you test connectivity and debug network issues from the command line?
Layer by layer: ping tests basic ICMP connectivity. traceroute (or tracepath) shows the network path and where packets are being dropped. curl -v tests HTTP endpoints with full request/response headers. telnet host port or nc -zv host port tests if a specific TCP port is reachable. ss -tuln checks local listening ports. ip addr verifies network interface configuration. ip route checks routing table. Start from the bottom (is the interface up?) and work up to the application layer.
Q: What is the difference between TCP and UDP? Give examples of when each is used.
TCP (Transmission Control Protocol) is connection-oriented and reliable: it guarantees delivery, ordering, and error checking via a three-way handshake and acknowledgments. Used for HTTP/HTTPS, SSH, databases, and email. UDP (User Datagram Protocol) is connectionless and faster: no handshake, no delivery guarantee, lower latency. Used for DNS queries, video streaming, VoIP, online gaming, and NTP. Choose TCP when data integrity matters; choose UDP when speed and low latency are more important than guaranteed delivery.
Shell Scripting
Q: What is the difference between $?, $!, $$, and $@?
$? is the exit code of the last command (0 = success, non-zero = failure). $! is the PID of the last background process. $$ is the PID of the current shell. $@ expands to all positional arguments as separate words (use "$@" with quotes to preserve arguments containing spaces). There is also $# (number of arguments) and $0 (script name). These are essential for writing robust shell scripts that handle errors and arguments correctly.
Q: How do you write an if statement in bash? What is the difference between [ ] and [[ ]]?
Basic syntax: if [[ condition ]]; then ... elif [[ condition ]]; then ... else ... fi. [ ] (single brackets) is the POSIX-compatible test command — portable but requires careful quoting. [[ ]] (double brackets) is a bash built-in with improvements: supports &&/|| operators, pattern matching ([[ $str == *.txt ]]), regex ([[ $str =~ ^[0-9]+$ ]]), and handles unquoted variables without word splitting. Prefer [[ ]] in bash scripts for safety and features.
Q: How do you loop over files in a directory? What pitfalls should you avoid?
Use for file in /path/to/dir/*.log; do echo "$file"; done. Critical pitfalls: never parse ls output (for f in $(ls)) because filenames with spaces or special characters will break. Always quote variables ("$file"). If the glob matches nothing, bash expands it literally; use shopt -s nullglob to get an empty list instead. For recursive processing, use find /path -name "*.log" -exec command {} \; or find ... | while read -r file; do ... done.
Q: What is set -euo pipefail and why should you use it?
This is the strict mode for bash scripts. set -e exits immediately if any command fails (non-zero exit). set -u treats unset variables as errors (catches typos). set -o pipefail makes a pipeline fail if any command in it fails (not just the last). Without these, scripts silently continue past errors. Put #!/usr/bin/env bash and set -euo pipefail at the top of every production script. It catches bugs that would otherwise cause silent data corruption or partial failures.
Q: How do you handle errors and exit codes in a shell script?
Every command returns an exit code: 0 for success, non-zero for failure. Check with $? or use if command; then ... else ... fi. Use trap 'cleanup_function' EXIT to run cleanup code when the script exits (for any reason). Use || for fallbacks: command || echo "failed". Use && for sequential success: cmd1 && cmd2. With set -e, unhandled failures exit the script. Override for specific commands: command || true to ignore failure.
System Administration
Q: A server's disk is 100% full. How do you diagnose and fix it?
Start with df -h to see which filesystem is full. Then find the biggest files: du -sh /* | sort -rh | head -10 and drill down into the largest directories. Common culprits: log files (/var/log), old kernels (/boot), package cache (/var/cache), or temp files (/tmp). Quick fixes: truncate a log with > /var/log/big.log (not rm, since the file handle may still be held), clean package cache with apt clean or yum clean all. Also check for deleted-but-open files with lsof +L1 which consume space until the process releases them.
Q: How do you check and troubleshoot high CPU or memory usage?
Use top or htop to see real-time CPU and memory per process. Sort by CPU (press P) or memory (press M) in top. Check load average with uptime and compare to core count (nproc). For memory: free -h shows total, used, available (note that "buff/cache" is reclaimable). For a specific process: pidstat -p PID 1 shows CPU/memory over time. Check for OOM kills with dmesg | grep -i oom. High wa (I/O wait) in top indicates the bottleneck is disk, not CPU.
Q: What are the main differences between su and sudo? Why is sudo preferred?
su (switch user) opens a new shell as another user (typically root) and requires that user's password. sudo runs a single command as root using your own password, then drops privileges. sudo is preferred because: 1) Root password doesn't need to be shared. 2) /var/log/auth.log records who ran what (accountability). 3) Fine-grained control via /etc/sudoers (limit which commands users can run). 4) Least privilege — you only elevate for the one command that needs it.
Q: Describe the Linux boot process from power on to login prompt.
1) BIOS/UEFI runs POST (Power-On Self-Test) and finds the boot device. 2) Bootloader (GRUB2) loads the kernel and initramfs into memory. 3) Kernel initializes hardware, mounts the root filesystem, and starts PID 1. 4) systemd (PID 1) reads unit files and starts services in parallel based on dependencies, working toward the default target (usually multi-user.target for servers or graphical.target for desktops). 5) getty/login service presents the login prompt. Check boot issues with journalctl -b (current boot) or systemd-analyze blame (slow services).
Q: How do you harden a Linux server for production? Name at least 5 steps.
1) Disable root SSH login (PermitRootLogin no in /etc/ssh/sshd_config) and use key-based authentication only. 2) Configure firewall (ufw/iptables) to allow only required ports. 3) Keep packages updated (unattended-upgrades for security patches). 4) Use fail2ban to block brute-force SSH attempts. 5) Remove unnecessary services (systemctl disable). 6) Set proper file permissions (no world-writable files). 7) Enable audit logging (auditd). 8) Configure SELinux or AppArmor for mandatory access control. 9) Use non-root users with sudo for daily operations.