Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 95 ยท Practice and Review

Linux and Bash Interview Questions and Answers

Prepare for Linux and Bash interviews with 50 concise questions and answers on the filesystem, permissions, processes, pipes and shell scripting pitfalls.

Interviews for developer, DevOps and sysadmin roles keep returning to the same Linux topics: how the filesystem is laid out, what permissions mean, how processes and pipes work, and which Bash mistakes bite in production. This page collects 50 questions in the order interviewers usually ask them, each with a short answer you could say out loud and, where it helps, a few lines of code.

A good answer has three parts: the definition in one sentence, the mechanism (why it works that way), and a pitfall or example that shows you have used it for real. Read each answer, then close the page and say it in your own words. The runnable examples prove the claims, so run them and change them.

Filesystem and files

1. What does "everything is a file" mean?

Regular files, directories, devices (/dev/null), pipes, sockets and even kernel information (/proc) are all reached through the same system calls: open, read, write, close. That is why cat, > and grep work on all of them. See the filesystem layout.

2. What is the difference between an absolute and a relative path?

An absolute path starts at the root / and means the same thing everywhere (/etc/hosts). A relative path starts at the current working directory (../notes/todo.txt). Scripts that run from cron or another directory should use absolute paths or cd to a known place first.

3. What do /etc, /var, /usr, /tmp and /home contain?

/etc holds system configuration, /var holds data that changes (logs, spools, caches), /usr holds installed programs and libraries, /tmp holds temporary files that may be deleted at any time, and /home holds user files. /proc and /sys are virtual views of the kernel.

4. What is an inode?

An inode is the file system record that stores everything about a file except its name: owner, permissions, size, timestamps and where the data blocks are. A directory is a table that maps names to inode numbers. Running out of inodes (df -i) can stop file creation even when there are free bytes.

A hard link is another name for the same inode, so deleting one name leaves the data reachable through the other. A symbolic link is a tiny file that stores a path; if the target disappears, the link dangles. Hard links cannot cross file systems and cannot point at directories. Details: links.

Bash Hard link versus symbolic link

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

6. What does rm -rf do and how do you make it safer?

It removes a directory tree recursively without asking and without complaining about missing files. There is no trash can. Safer habits: run ls with the same glob first, quote variables, and guard with ${dir:?} so an empty variable aborts instead of becoming rm -rf /. See copying, moving and deleting.

7. How do you find files bigger than 10 MB modified in the last day?

find /path -type f -size +10M -mtime -1. Use -print0 with xargs -0 (or -exec ... {} +) so that names with spaces or newlines survive. See find and locate.

8. How do you find out which directory is using the most space?

du -h --max-depth=1 | sort -h, repeated in the biggest child. df -h tells you which file system is full, du tells you who filled it. Deleted-but-still-open files are the classic reason the two disagree. See disk usage.

Permissions and users

9. How do you read -rwxr-x---?

The first character is the type (- regular file, d directory, l link). Then three triplets for the owner, the group and everyone else, each with read, write and execute. So the owner can do everything, the group can read and execute, others get nothing. Octal: r=4, w=2, x=1, so this is 750.

10. What does the execute bit mean on a directory?

It means you may enter the directory and reach files inside by name. The read bit lets you list names. A directory with r-- lets you see names but not open anything; with --x you can open a file if you already know its name.

11. What is umask?

A mask of permission bits that are removed from newly created files and directories. With the usual 022, files start from 666 and become 644, and directories start from 777 and become 755.

Bash chmod, octal modes and umask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

12. What are setuid, setgid and the sticky bit?

Setuid on an executable makes it run with the owner's identity (that is how passwd can edit protected files). Setgid on a program does the same for the group; on a directory it makes new files inherit the directory's group. The sticky bit on a directory (/tmp) lets only a file's owner or root delete or rename it.

13. What is the difference between su, sudo and being root?

su switches to another user after you give that user's password. sudo runs one command with another identity (usually root) after you prove who you are, as allowed by sudoers, and logs it. Working as root all the time removes every safety net, so prefer least privilege. See users, groups and sudo.

14. A script says Permission denied. What do you check?

First whether the file has the execute bit (ls -l), or run it as bash script.sh. Then the x bit on every directory in the path, ownership, and a noexec mount on that file system. If the shebang points to an interpreter that does not exist, the message looks the same.

Text processing

15. What does grep return when nothing matches?

Exit status 1 (and no output). Status 0 means at least one match, and 2 means an error. In a script with set -e, an unmatched grep therefore ends the script unless you handle it with if grep -q ... or || true. See grep.

16. What is the difference between grep, grep -E and grep -F?

Plain grep uses basic regular expressions (you must escape +, ?, |, (). -E uses extended expressions where those are special without a backslash. -F treats the pattern as a fixed string, which is fastest and safest for text you did not write yourself.

17. How do you count how often each word appears and show the top three?

Split into words, sort, count adjacent duplicates, sort by count:

Bash Word frequency with sort and uniq

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

uniq only collapses adjacent lines, so the first sort is not optional. The second key (-k2) makes ties come out in a stable alphabetical order. See sort, uniq, cut and wc.

18. What is the difference between sed and awk?

sed is a stream editor built around substitutions and line addresses (s/old/new/, 3,5d). awk is a small programming language that splits each line into fields and is better at columns, sums and reports. Use sed to change text, awk to calculate with it. See sed and awk.

19. How do you print the second column of a file and sum the third?

awk '{print $2}' file and awk '{s += $3} END {print s}' file. Awk splits on runs of blanks by default; use -F, for simple comma-separated data (quoted CSV fields need a real CSV tool).

20. How do you replace text in a file in place, safely?

sed -i.bak 's/old/new/g' file edits the file and keeps file.bak. -i without a suffix is GNU behavior; BSD and macOS sed need -i '', so portable scripts write to a temporary file and mv it over the original.

21. What does cut -d: -f1,7 /etc/passwd do?

It splits each line at colons and prints the first and seventh fields: the user name and login shell. cut takes single-character delimiters and cannot treat runs of spaces as one, which is where awk is the better tool.

22. How do you compare two files?

diff -u old new prints a unified diff you can apply with patch; cmp reports the first differing byte; comm compares two sorted lists in three columns; sha256sum tells you quickly whether two files are identical. See diff and patch.

Pipes and redirection

23. What are file descriptors 0, 1 and 2?

Standard input, standard output and standard error. Programs write results to 1 and diagnostics to 2, which lets you redirect them separately: cmd > out.txt 2> err.txt. See standard streams.

24. What is the difference between > and >>?

> truncates the file first and then writes. >> appends. The shell truncates before the command runs, so sort file > file leaves you with an empty file.

25. What is the difference between 2>&1 > file and > file 2>&1?

Redirections are processed left to right. > file 2>&1 points stdout at the file, then copies that to stderr, so both land in the file. 2>&1 > file first points stderr at the current stdout (the terminal or pipe), and only then moves stdout to the file.

Bash Why the order of redirections matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

26. What does a pipe do, and do the commands run one after another?

A pipe connects the stdout of one process to the stdin of the next through a kernel buffer. All commands in a pipeline start at the same time and run concurrently; a fast producer blocks when the buffer (64 KiB on Linux) is full. See pipes.

27. What is the exit status of a pipeline?

By default it is the status of the last command, so failures earlier in the pipe are hidden. set -o pipefail makes it the last non-zero status, and the PIPESTATUS array holds every stage's status.

Bash Pipeline exit status and pipefail

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

28. What is /dev/null?

A device that discards everything written to it and returns end-of-file when read. Use cmd > /dev/null to silence output and cmd 2> /dev/null to silence errors (but remember that you then cannot see why it failed).

29. What is a here-document and what does quoting the delimiter change?

<<EOF feeds the following lines to a command's stdin. With an unquoted delimiter the shell expands $var and $(cmd) inside; with <<'EOF' the text is literal. <<- strips leading tabs so you can indent. See here-documents.

30. What is the difference between a pipe and a named pipe?

An ordinary pipe exists only between related processes in one command line. A named pipe (FIFO, made with mkfifo) has a name in the filesystem, so unrelated processes can connect to it. Opening one blocks until the other end is opened.

31. What is xargs for and why use -0?

Many commands take arguments, not stdin. xargs turns input lines into arguments. Without -0 it splits on blanks and treats quotes specially, which breaks names with spaces; find -print0 | xargs -0 uses NUL bytes, which cannot appear in a file name. See xargs.

Bash Safe file handling with find, print0 and xargs -0

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Processes and the system

The naive version cuts my notes.txt and the file with a newline in its name into pieces. The NUL-separated version prints three intact names (%q shows the newline as $'\n').

32. What is a process, and how does it differ from a program?

A program is a file on disk. A process is a running instance with its own PID, memory, open files, environment and current directory. One program can have many processes. Each process (except PID 1) has a parent, which you can see with ps -o pid,ppid,cmd. See processes.

33. How does the shell run an external command?

It calls fork to clone itself, the child calls exec to replace its code with the program, and the parent waits for the exit status (unless the command ends with &). Builtins such as cd run inside the shell itself, which is why cd could not be a separate program.

34. What are zombie and orphan processes?

A zombie has exited but its parent has not yet collected its exit status with wait; it uses no memory, only a process table slot. An orphan is a running process whose parent died; it is adopted by PID 1 (or a subreaper). You cannot kill a zombie, you make the parent reap it or end the parent.

35. What is the difference between SIGTERM, SIGKILL and SIGINT?

SIGINT (2) is what Ctrl+C sends and SIGTERM (15) is the polite default of kill; both can be caught so programs clean up. SIGKILL (9) cannot be caught or ignored, the kernel simply ends the process, so no cleanup happens. Try TERM first, KILL last. See kill and signals.

36. How do you run something in the background and wait for it?

Append &, remember its PID in $!, and collect it with wait. A background job still dies with the terminal's SIGHUP unless you use nohup, disown or a terminal multiplexer.

Bash Background jobs, wait and exit statuses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

37. What is the difference between $!, $$ and $?

$! is the PID of the most recent background job, $$ is the PID of the current shell, and $? is the exit status of the last command. $# counts arguments and $@ expands to all of them. See variables.

38. How do you see what is listening on a port or using memory?

ss -ltnp lists listening TCP sockets with the owning process, lsof -i :8080 does the same for one port, ps aux --sort=-%mem | head shows memory hogs and free -h the totals. On older systems netstat plays the role of ss. See networking basics.

39. What does nohup do?

It makes a command ignore SIGHUP and, if stdout is a terminal, redirects it to nohup.out. That keeps long jobs alive after you log out. For services, a process supervisor such as systemd is the modern answer.

40. What is a systemd unit, and how do you read its logs?

A unit is a configuration file describing something systemd manages: a service, a timer, a mount. systemctl status app and systemctl restart app control it, and journalctl -u app -f follows its log. See packages, services and systemd.

41. How does cron differ from a systemd timer?

Both schedule jobs. Cron uses five time fields (minute hour day month weekday) in a crontab, runs with a minimal environment and mails output. A timer is a unit that triggers a service, with dependencies, logging in the journal and options like Persistent=true to catch up after downtime.

Scripting and pitfalls

42. What does the shebang line do?

#!/usr/bin/env bash on the first line tells the kernel which interpreter to run when the file is executed directly. Without it (or when you run sh script), the script may run under a different shell with different features. See your first script.

43. Why do you quote variables?

Unquoted expansions go through word splitting and globbing, so a value with spaces becomes several arguments and * becomes a file list. Writing "$var" and "$@" keeps each value as one word. See quoting.

Bash The unquoted variable bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

44. What is the difference between "$@" and "$*"?

"$@" expands to each argument as a separate word, preserving spaces inside them. "$*" joins all arguments into one word using the first character of IFS. Use "$@" to pass arguments along.

45. What is the difference between [ ] and [[ ]]?

[ is an ordinary command (a synonym for test), so its arguments are expanded like any other and need quoting. [[ is Bash syntax with special parsing: no word splitting inside, pattern matching with ==, regular expressions with =~, and &&/|| inside the brackets. It is not available in plain POSIX sh. See conditionals.

46. What does set -euo pipefail do and why is it not a cure-all?

-e exits on a failing command, -u makes unset variables an error and pipefail reports failures inside pipelines. But -e is ignored in if/while conditions, in the left side of && and ||, and in some command substitutions, so it can give false confidence. Treat it as a safety net, not as error handling. See exit codes and errors.

47. Why does a variable set inside ... | while read vanish?

Each side of a pipe runs in a subshell, and a subshell's variables disappear when it exits. Read from a process substitution or a file instead, or enable shopt -s lastpipe in a script. See subshells.

Bash The pipeline subshell gotcha

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The pipe version prints count=0, the other two print 3 and 4.

48. How do you clean up temporary files even if the script fails?

Create them with mktemp (never a fixed name like /tmp/out), and register a handler: tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT. The EXIT trap runs on normal exit, on exit after an error and on termination by most signals. See signals and trap.

49. Why is parsing the output of ls a bad idea?

File names can contain spaces, newlines and any byte but / and NUL, and ls output is for humans. Use globs (for f in *.txt), find -print0, or stat -c for metadata. Also guard the glob with [[ -e $f ]] or shopt -s nullglob for the no-match case.

50. When should you stop writing a Bash script and use another language?

When you need real data structures, JSON or CSV parsing, unit tests at scale, concurrency beyond simple jobs, or the script passes roughly 100 to 200 lines. Bash is excellent glue for commands, files and pipelines; Python, Go or Node.js are better for logic. See designing maintainable scripts.

System administration questions

51. How does command history work?

Bash keeps the commands of a session in memory (up to HISTSIZE, default 500 or 1000) and appends them to ~/.bash_history (up to HISTFILESIZE) when the shell exits. history lists them with numbers, !42 re-runs entry 42, !! repeats the last command, !$ is its last argument, Ctrl+R searches backwards, and history -c clears the session. Set HISTCONTROL=ignoreboth to skip duplicates and commands starting with a space, which is also a way to keep a secret off the record. See prompts and completion.

52. What is stored in /var?

Variable data that grows while the system runs: logs (/var/log), package caches (/var/cache), mail and print queues (/var/spool), databases and service data (/var/lib), lock and PID files (/var/run, usually a link to /run) and temporary files that must survive a reboot (/var/tmp). A full /var is a common cause of outages, so it often gets its own partition. See the filesystem layout.

53. What are nice and renice?

Niceness is a process's willingness to give up CPU, from -20 (greedy, highest priority) to 19 (very nice, lowest priority); the default is 0. nice -n 10 command starts a command with lower priority, renice -n 5 -p PID changes a running one, and only root may lower the number. It matters only when CPUs are contended. ionice does the same for disk I/O. See Processes.

54. What are jobs, bg and fg?

A job is a pipeline your shell started. Ctrl+Z stops the foreground job, bg resumes it in the background, fg %1 brings job 1 back to the foreground, and jobs lists them (%1, %+ for the current job, %?text to match by command text). Jobs belong to one shell session, unlike PIDs, which are system-wide. See jobs and background tasks.

55. What is SSH, and how does it keep a connection safe?

SSH is an encrypted protocol for remote shells, file transfer and tunnels (port 22). Asymmetric key pairs authenticate the server and you, a shared secret then drives fast symmetric encryption, and message checksums detect tampering. Use keys rather than passwords, disable root login and check host-key fingerprints. See SSH and remote work.

56. What is dependency management?

A package depends on libraries and other packages; the package manager (apt, dnf, pacman) resolves the whole tree, installs what is missing, refuses to remove what something else needs, and keeps a database so you can ask which package owns a file (dpkg -S, rpm -qf). Low-level tools (dpkg -i) do not resolve dependencies; high-level tools do. See packages and services.

57. What is GRUB?

GRUB 2 is the usual boot loader: it shows the menu, loads the kernel and the initramfs and passes the kernel command line. Its generated grub.cfg comes from /etc/default/grub and /etc/grub.d/ (rebuild with update-grub or grub2-mkconfig). Alternatives are systemd-boot, SYSLINUX and, historically, LILO. See boot and the kernel.

58. What is systemd?

The init system (PID 1) and service manager of most distributions. It starts units (services, mounts, timers, sockets, targets) in parallel according to their dependencies, supervises and restarts services, collects logs in the journal (journalctl) and exposes everything through systemctl. It replaced SysV init scripts and runlevels. See packages and services.

59. What is LVM?

The Logical Volume Manager puts a flexible layer between disks and file systems: disks or partitions become physical volumes, are pooled into a volume group, and logical volumes are carved out of the pool. Logical volumes can be resized online, span several disks and be snapshotted. See LVM and file systems.

60. What is the OOM killer?

When memory and swap are exhausted, the kernel's out-of-memory killer picks a process with a high oom_score (large and not protected) and ends it with SIGKILL so that the system keeps running. The log line Out of memory: Killed process 1234 (java) appears in dmesg and the journal. Adjust a process's odds with /proc/PID/oom_score_adj (-1000 protects, +1000 makes it the first victim) and prevent the cause with limits (cgroups, MemoryMax= in a unit) and more RAM. See disks and logs.

61. What is a zombie process?

A child that has exited but whose parent has not yet collected its exit status with wait. It uses no CPU or memory except a process-table entry and shows as Z in ps. You cannot kill a zombie (it is already dead); fix or end the parent, and init will reap the orphan. See Processes.

62. How do you find which process listens on a port?

ss -tulpn | grep :8080 (add sudo to see other users' processes), or lsof -i :8080. The last column names the PID and program. See network troubleshooting.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A command is written cmd 2>&1 > out.txt in a terminal. Where does stderr go?

    Redirections apply left to right. 2>&1 points stderr at what stdout is at that moment (the terminal), and only afterwards does > out.txt move stdout to the file.
  2. 2. Why does uniq -c usually follow a sort?

    uniq compares each line only with the previous one, so equal lines must be next to each other, which is what sort guarantees.
  3. 3. After rm a.txt, a hard link hard.txt and a symbolic link soft.txt were both created from it earlier. What happens?

    A hard link is another name for the same inode, so the data survives until the last name is gone. A symbolic link only stores the path a.txt, which no longer exists.
  4. 4. Which signal cannot be caught or ignored by a process?

    SIGKILL (9) and SIGSTOP are handled by the kernel itself, so the process gets no chance to clean up.
  5. 5. Why is for f in $(ls) considered a bug-prone idiom?

    Command substitution output undergoes word splitting and globbing, so names with spaces become several words. Use for f in * or find -print0 instead.

Summary

  • Know the vocabulary: inode, hard and symbolic link, file descriptor, PID, signal, exit status.
  • Permissions are three triplets (user, group, other); umask removes bits from new files; the x bit on a directory means "may enter".
  • Redirections run left to right; pipes connect concurrent processes; pipefail and PIPESTATUS reveal hidden failures.
  • Use sort | uniq -c | sort -nr for counts, sed for substitution, awk for columns, find -print0 | xargs -0 for safe bulk work.
  • Quote every expansion, avoid parsing ls, clean up with mktemp and trap ... EXIT, and remember that set -e has gaps.
  • Practice out loud: say the definition, the mechanism and one pitfall for each topic.

That wraps up the Linux and Bash tutorial. Keep the cheat sheet close, redo the practice problems from time to time, and build something real with the shell.