Linux & Shell Scripting MCQ
Test your Linux and Shell Scripting knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.
How This Practice Test Works
Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.
Curated by Tech Baithak Editorial Team · Last updated: June 2026
1
What does the "pwd" command do?
Correct Answer
Prints the current working directory
Explanation
"pwd" (print working directory) outputs the absolute path of the directory the user is currently in.
2
What does the "ls -l" command display?
Correct Answer
A detailed (long format) listing of files and directories, including permissions, owner, size, and modification date
Explanation
"ls -l" shows a long-format listing with file permissions, number of links, owner, group, size, and last modified timestamp for each file.
3
What is the purpose of the "cd" command?
Correct Answer
To change the current working directory
Explanation
"cd" (change directory) navigates the shell's current working directory to the specified path.
4
In Linux, what does the command "cat file.txt" do?
Correct Answer
Displays the contents of file.txt to standard output
Explanation
"cat" (concatenate) outputs the content of one or more files to the terminal, and can also be used to concatenate multiple files together.
5
What does the "mkdir" command do?
Correct Answer
Creates a new directory
Explanation
"mkdir" (make directory) creates one or more new directories with the specified names.
6
What is the purpose of the "rm" command?
Correct Answer
To remove (delete) files or directories
Explanation
"rm" removes files (or directories with -r) from the filesystem; deleted files are not moved to a trash/recycle bin by default, so use caution.
7
What does the command "chmod 755 file.sh" do?
Correct Answer
Changes the file's permissions so the owner can read/write/execute, and group/others can read/execute
Explanation
chmod 755 sets permissions to rwxr-xr-x: the owner gets read, write, and execute (7), while group and others get read and execute (5 each).
8
What is the role of the "root" user in Linux?
Correct Answer
The superuser account with full administrative privileges over the entire system
Explanation
The root user has unrestricted access to all files, commands, and system resources, and is used for administrative tasks; misuse can be dangerous, so "sudo" is often preferred for occasional elevated tasks.
9
What does the "sudo" command do?
Correct Answer
Allows a permitted user to execute a command with the security privileges of another user, typically the superuser
Explanation
"sudo" (superuser do) lets authorized users run individual commands with elevated (often root) privileges, logging the action for accountability.
10
What is a "shell" in Linux?
Correct Answer
A command-line interpreter that provides a user interface for accessing the operating system's services
Explanation
A shell (e.g. bash, zsh, sh) reads commands typed by the user (or from a script) and executes them, acting as an interface between the user and the kernel.
11
What does the shebang line "#!/bin/bash" at the top of a script indicate?
Correct Answer
It specifies which interpreter should be used to execute the script
Explanation
The shebang line tells the operating system which interpreter (here, /bin/bash) to use when running the script, allowing it to be executed directly without specifying the interpreter manually.
12
How do you make a shell script executable?
Correct Answer
Run "chmod +x scriptname.sh" to add execute permission
Explanation
"chmod +x" adds the execute permission to a file, allowing it to be run directly (e.g. "./scriptname.sh") rather than only being readable.
13
What is the purpose of an environment variable like "$PATH"?
Correct Answer
It contains a list of directories that the shell searches when looking for executable commands
Explanation
When you type a command, the shell searches each directory listed in $PATH (in order) for an executable with that name.
14
What does the "grep" command do?
Correct Answer
Searches for lines matching a pattern within files or input
Explanation
"grep" searches input (files or piped data) for lines matching a given pattern (often a regular expression) and prints matching lines.
15
What is the purpose of the pipe symbol "|" in a shell command?
Correct Answer
It takes the output of one command and uses it as the input to another command
Explanation
The pipe "|" connects the standard output of the command on its left to the standard input of the command on its right, enabling command chaining like "ls | grep .txt".
16
What is the difference between ">" and ">>" in shell redirection?
Correct Answer
">" redirects output to a file, overwriting its existing contents, while ">>" appends output to the end of the file without erasing existing content
Explanation
">" truncates and overwrites the target file with new output, while ">>" preserves existing content and adds the new output after it.
17
What does the "cp" command do?
Correct Answer
Copies files or directories from one location to another
Explanation
"cp source destination" copies a file (or, with -r, a directory) to a new location, leaving the original intact.
18
What does the "mv" command do?
Correct Answer
Moves or renames files and directories
Explanation
"mv" moves a file/directory to a new location, or renames it if the destination is in the same directory with a different name.
19
What is the home directory typically represented by in the shell?
Correct Answer
The tilde symbol (~)
Explanation
The tilde "~" is a shorthand that expands to the current user's home directory (e.g. /home/username), usable in commands like "cd ~".
20
What is the purpose of the "man" command?
Correct Answer
To display the manual page (documentation) for a command or program
Explanation
"man <command>" opens the manual page for that command, providing detailed documentation on its usage, options, and examples.
21
What does the "echo" command do in a shell script?
Correct Answer
It prints (displays) the given text or variable value to standard output
Explanation
"echo" outputs its arguments to the terminal, commonly used to display messages or variable values, e.g. "echo $HOME".
22
How do you assign a value to a variable in a bash script?
Correct Answer
name="value" (no spaces around the equals sign)
Explanation
In bash, variable assignment must have no spaces around "="; "name = value" would instead be interpreted as running a command "name" with arguments "=" and "value".
23
How do you access the value of a variable named "name" in a bash script?
Correct Answer
$name or ${name}
Explanation
Prefixing a variable name with "$" (optionally enclosed in braces, "${name}") expands to its value when referenced in commands or strings.
24
What is the purpose of the "touch" command?
Correct Answer
To create a new empty file if it doesn't exist, or update the modification timestamp of an existing file
Explanation
"touch filename" creates an empty file if it doesn't already exist, or updates the access/modification timestamps of an existing file without changing its content.
25
What does the "ps" command display?
Correct Answer
A list of currently running processes
Explanation
"ps" displays information about active processes, including their process IDs (PIDs), terminal, status, and command name, useful for monitoring and troubleshooting.
26
What is the purpose of the "kill" command?
Correct Answer
To send a signal (often to terminate) to a process, identified by its process ID (PID)
Explanation
"kill <pid>" sends a signal (SIGTERM by default) to the specified process, typically requesting it to terminate gracefully; "kill -9" sends SIGKILL for a forceful termination.
27
What does an "if" statement check in a bash script, and how is its condition typically written?
Correct Answer
Conditions are written using square brackets, e.g. "if [ $x -gt 5 ]; then ... fi", testing whether the enclosed expression evaluates to true
Explanation
In bash, "[ ]" (or "[[ ]]" for extended tests) evaluates the enclosed expression; combined with "if ... then ... fi", it controls conditional execution based on the result.
28
What is the purpose of a "for" loop in a shell script?
Correct Answer
To repeat a block of commands for each item in a list or range of values
Explanation
A "for" loop (e.g. "for i in 1 2 3; do echo $i; done") iterates over a sequence of values, executing the loop body once for each item.
29
What does the "wc -l" command count?
Correct Answer
The number of lines in the input
Explanation
"wc" (word count) with the "-l" flag counts the number of newline characters (lines) in the given file or input stream.
30
What is the purpose of the "exit" command (or "exit N") at the end of a script?
Correct Answer
It terminates the script and sets its exit status to N (0 typically meaning success, non-zero meaning failure)
Explanation
"exit N" ends script execution and returns exit code N to the calling process; conventionally, 0 indicates success and any non-zero value indicates an error condition.
31
What is the difference between a "relative path" and an "absolute path"?
Correct Answer
An absolute path starts from the root directory ("/") and fully specifies a location, while a relative path is interpreted relative to the current working directory
Explanation
Absolute paths (e.g. "/home/user/file.txt") unambiguously specify a location regardless of the current directory, while relative paths (e.g. "../file.txt") depend on where the command is run from.
32
What does "Ctrl+C" typically do when a process is running in the foreground of a terminal?
Correct Answer
It sends an interrupt signal (SIGINT) to the foreground process, typically terminating it
Explanation
Ctrl+C sends SIGINT to the foreground process group, which by default causes the process to terminate, though programs can choose to handle or ignore this signal.
33
What does "Ctrl+Z" do to a running foreground process?
Correct Answer
It suspends (pauses) the process, sending it to the background in a stopped state, which can be resumed later with "fg" or "bg"
Explanation
Ctrl+Z sends SIGTSTP, pausing the process; "fg" resumes it in the foreground, or "bg" resumes it in the background while freeing up the terminal.
34
What is the purpose of the "df -h" command?
Correct Answer
It shows disk space usage of mounted filesystems in a human-readable format
Explanation
"df" (disk free) reports filesystem disk space usage, and "-h" displays sizes in human-readable units (KB, MB, GB) rather than raw byte counts.
35
What does the "tar" command commonly do?
Correct Answer
It is used to archive multiple files into a single file (often combined with compression like gzip)
Explanation
"tar" (tape archive) bundles multiple files and directories into a single archive file, often combined with compression tools (e.g. "tar -czf archive.tar.gz folder/").
36
What is the purpose of the "find" command?
Correct Answer
To search for files and directories based on criteria like name, type, size, or modification time
Explanation
"find /path -name \"*.txt\"" recursively searches a directory tree for files/directories matching specified criteria such as name pattern, type, size, or timestamps.
37
What is the meaning of a "hidden file" in Linux, and how is it identified?
Correct Answer
A hidden file is any file or directory whose name begins with a dot (".") and is not shown by default in directory listings (unless using "ls -a")
Explanation
Files starting with "." (like ".bashrc") are considered hidden by convention and are excluded from normal "ls" output, but they can be viewed with "ls -a" and accessed normally.
38
What does the "whoami" command output?
Correct Answer
The current username
Explanation
"whoami" prints the username associated with the current effective user ID, useful for confirming which user context a script or session is running under.
39
What does the "head" command do by default?
Correct Answer
Displays the first 10 lines of a file
Explanation
"head" prints the beginning of a file, showing 10 lines by default; the number of lines can be changed with "-n", e.g. "head -n 5 file.txt".
40
What is the purpose of the "history" command in bash?
Correct Answer
It displays a list of previously executed commands in the current shell session
Explanation
"history" lists previously run commands with line numbers, which can be re-executed using "!<number>" or recalled with the up arrow key.
1
What is the difference between a "hard link" and a "symbolic link" (symlink)?
Correct Answer
A hard link directly references the same inode as the original, so the data persists even if the original name is deleted; a symbolic link is a separate file holding a path to another file, and breaks if the target is removed
Explanation
Hard links share the same inode as the original (so the data persists as long as any hard link exists), and cannot cross filesystem boundaries, while symlinks are pointers to a path that become "dangling" if the target is deleted or moved.
2
What is the purpose of "process substitution" and "command substitution" in bash, e.g. the difference between `$(command)` and backticks?
Correct Answer
`$(command)` and backticks both perform command substitution, capturing the output of a command to use as a string, but `$(...)` is generally preferred because it supports nesting more cleanly and avoids tricky escaping rules associated with backticks
Explanation
Both forms substitute the output of the enclosed command into the surrounding command line, but `$(...)` handles nested substitutions and quoting more reliably, making it the modern preferred syntax.
3
What is the difference between "$@" and "$*" when referring to script arguments in bash?
Correct Answer
Quoted "$@" expands each argument as a separate, individually-quoted word, while quoted "$*" joins all arguments into one string separated by the first character of IFS — this matters when looping over arguments containing spaces
Explanation
Quoted "$@" expands to separate quoted strings ("$1" "$2" ...), preserving arguments with spaces as individual items, while quoted "$*" joins all arguments into one string — important when iterating with "for arg in "$@"".
4
What is the purpose of "set -e" in a bash script?
Correct Answer
It causes the script to exit immediately if any command exits with a non-zero status, helping catch errors early rather than continuing execution after a failure
Explanation
"set -e" (errexit) makes the script abort on the first command that fails (returns non-zero), which is commonly used to prevent scripts from continuing in an unexpected or broken state after an error.
5
What is the purpose of "trap" in bash scripting?
Correct Answer
To capture and respond to signals or events (like EXIT, SIGINT, or ERR), allowing a script to run cleanup code before terminating
Explanation
"trap 'cleanup_function' EXIT" registers a command to run when the script exits (normally or due to a signal), commonly used to clean up temporary files or release resources.
6
What is the difference between "sed" and "awk", and what is each typically used for?
Correct Answer
"sed" is a stream editor for simple line-based text transformations like substitutions, while "awk" is a fuller pattern-scanning language suited for extracting and manipulating fields from structured text such as columns
Explanation
"sed" excels at line-based find/replace operations (e.g. "sed 's/foo/bar/g' file"), while "awk" provides a full scripting language for field-based processing, calculations, and formatted reporting (e.g. "awk '{print $1}' file").
7
What does the command "ls -la | grep '^d'" accomplish?
Correct Answer
It lists all files and directories in long format, then filters the output to show only lines starting with "d" (which represents directories in the permissions field)
Explanation
In "ls -l" output, the first character of the permissions string indicates file type — "d" for directories. Piping to "grep '^d'" filters lines where that first character is "d", effectively listing only directories.
8
What is the difference between a "soft link limit" issue caused by symlink loops, and how does "find" or "cp" typically handle such loops by default?
Correct Answer
A symlink loop happens when a link points back to one of its own ancestor directories, risking infinite recursion; "find" does not follow symlinks by default during traversal, avoiding loops unless told to with "-L"
Explanation
Because following every symlink during a recursive traversal could create infinite loops if a link points back into its own path, tools like "find" avoid following symlinks unless explicitly instructed (with flags like "-L" or "-follow"), which then requires care to avoid infinite recursion.
9
What is the purpose of "cron" and a "crontab" file?
Correct Answer
Cron is a time-based job scheduler that runs commands or scripts automatically at specified intervals defined in a crontab file, which uses a specific syntax to define minute, hour, day, month, and weekday schedules
Explanation
Cron reads schedule entries from crontab files (e.g. "0 2 * * * /path/to/script.sh" runs daily at 2 AM) and executes the associated commands at the specified times, commonly used for backups, log rotation, and maintenance tasks.
10
What is the difference between "su" and "su -" (or "su -l")?
Correct Answer
"su" switches the user but retains the current shell's environment variables (like PATH and working directory), while "su -" (login shell) resets the environment to match a fresh login as the target user, including their home directory and profile scripts
Explanation
"su -" simulates a full login as the target user, sourcing their shell profile files and switching to their home directory, while plain "su" keeps the calling user's environment, which can lead to unexpected PATH or directory issues.
11
What is the purpose of "xargs"?
Correct Answer
It builds and executes command lines from standard input, often used to pass a list of items (e.g. from "find" or "grep") as arguments to another command
Explanation
"xargs" reads items from standard input (often separated by whitespace or newlines) and uses them as arguments to build and run commands, e.g. "find . -name '*.tmp' | xargs rm" deletes all matched files.
12
What is the difference between "/etc/passwd" and "/etc/shadow"?
Correct Answer
"/etc/passwd" contains basic user account information (username, UID, GID, home directory, shell) and is world-readable, while "/etc/shadow" stores the actual (hashed) password data and is restricted to root for security
Explanation
Separating password hashes into "/etc/shadow" (readable only by root) from the world-readable "/etc/passwd" (needed by many programs to look up user info) improves security by preventing unprivileged users from accessing password hashes.
13
What does the "&" symbol at the end of a command do in bash?
Correct Answer
It runs the command in the background, returning control of the terminal immediately while the command continues executing
Explanation
Appending "&" to a command runs it as a background job, allowing the user to continue interacting with the shell while the command executes; "jobs" and "fg"/"bg" can manage background jobs.
14
What is the purpose of "$?" in bash?
Correct Answer
It holds the exit status (return code) of the most recently executed command, where 0 typically indicates success and non-zero indicates failure
Explanation
After any command runs, "$?" contains its exit code, commonly checked in scripts to determine whether a previous command succeeded (0) or failed (non-zero) before proceeding.
15
What is the difference between "while" and "until" loops in bash?
Correct Answer
A "while" loop continues executing as long as its condition is true, while an "until" loop continues executing as long as its condition is false (i.e. it stops once the condition becomes true)
Explanation
"while [ condition ]; do ... done" runs while the condition is true, whereas "until [ condition ]; do ... done" runs while the condition is false, stopping as soon as it becomes true — they are logical opposites of each other.
16
What is the purpose of "/dev/null"?
Correct Answer
A special device file that discards all data written to it and returns end-of-file immediately when read, often used to suppress output
Explanation
Redirecting output to "/dev/null" (e.g. "command > /dev/null 2>&1") discards both stdout and stderr, useful when you want to run a command without seeing its output.
17
What is the difference between "file descriptors" 0, 1, and 2 in Unix-like systems?
Correct Answer
0 represents standard input (stdin), 1 represents standard output (stdout), and 2 represents standard error (stderr) — these are the default I/O streams every process starts with
Explanation
These three standard file descriptors are conventionally assigned: stdin (0) for input, stdout (1) for normal output, and stderr (2) for error messages, and can be individually redirected (e.g. "2>error.log").
18
What does the command "chown user:group file.txt" do?
Correct Answer
It changes both the owning user and group of file.txt to the specified user and group
Explanation
"chown" changes the ownership of a file or directory; specifying "user:group" updates both the owning user and the owning group in one command.
19
What is the purpose of "alias" in bash, e.g. "alias ll='ls -la'"?
Correct Answer
It creates a shortcut name that the shell expands to a longer command, useful for frequently used commands or commonly-used options — aliases are typically defined in shell config files like ~/.bashrc to persist across sessions
Explanation
Aliases provide convenient shortcuts (e.g. "ll" for "ls -la") within the shell session that defines them; to persist across sessions, they're typically added to shell startup files like ~/.bashrc or ~/.zshrc.
20
What is the purpose of "export" when used with a variable in bash, e.g. "export VAR=value"?
Correct Answer
It marks the variable as an "environment variable" that will be inherited by child processes spawned from the current shell, as opposed to a regular shell variable which is local to the current shell only
Explanation
Without "export", a variable is only visible in the current shell; exporting it adds it to the environment passed to any subprocesses (like scripts or programs) launched from that shell.
21
What is the difference between "*.txt" and ".*" as wildcard patterns in bash globbing?
Correct Answer
"*.txt" matches any filename ending in ".txt" (excluding hidden files by default), while ".*" matches any filename starting with a dot, which includes hidden files like ".bashrc" as well as the special entries "." and ".."
Explanation
Bash glob patterns don't match dotfiles with "*" unless explicitly using a pattern starting with "."; ".*" matches anything starting with a dot, including "." and ".." themselves, which is a common gotcha when using "rm .* " accidentally.
22
What does the "uniq" command do, and what is a common gotcha when using it?
Correct Answer
"uniq" filters out adjacent duplicate lines from sorted input; a common gotcha is that it only removes consecutive duplicates, so input often needs to be sorted first (e.g. "sort file | uniq") to remove all duplicates regardless of order
Explanation
Because "uniq" only compares adjacent lines, non-adjacent duplicates won't be removed unless the input is sorted first, making "sort | uniq" a common idiom for true deduplication.
23
What is the purpose of "ssh-keygen" and public/private key authentication for SSH?
Correct Answer
"ssh-keygen" generates a public/private key pair; the public key goes on the server (in ~/.ssh/authorized_keys), while the private key, kept secret on the client, proves identity during login for password-less authentication
Explanation
SSH public key authentication relies on asymmetric cryptography: the server verifies a signature made with the client's private key against the corresponding public key it has on file, avoiding the need to transmit passwords.
24
What is the purpose of "/etc/fstab"?
Correct Answer
A configuration file that defines how disk partitions, devices, and remote filesystems should be automatically mounted at boot time, including mount points and options
Explanation
"/etc/fstab" (file system table) specifies which filesystems to mount automatically at boot, their mount points, filesystem types, and mount options.
25
What does the command "ps aux | grep nginx" accomplish, and what is a common caveat?
Correct Answer
It lists all running processes (in BSD-style format) and filters the output for lines containing "nginx"; a common caveat is that the "grep nginx" command itself may appear in the results as a process matching its own search term
Explanation
"ps aux" lists all processes with detailed info, and piping to "grep nginx" filters for matching lines; since "grep nginx" itself contains the string "nginx", it often shows up as a false match in the results.
26
What is the purpose of "background jobs" and the "nohup" command together, e.g. "nohup long_script.sh &"?
Correct Answer
Running a command with "&" backgrounds it, but it may still get a SIGHUP and terminate if the terminal closes; "nohup" prevents the process from receiving SIGHUP, letting it keep running after logout
Explanation
Without "nohup", background processes started from an interactive shell can be terminated by SIGHUP when the terminal closes; "nohup" (or tools like "disown", "screen", or "tmux") helps processes survive session disconnection.
27
What is the purpose of "diff" command, and what does its typical output represent?
Correct Answer
"diff file1 file2" compares the contents of two files line by line and outputs the differences, showing which lines need to be added, removed, or changed to transform one file into the other
Explanation
"diff" produces output describing line-by-line differences between two files, often used to review code changes or generate patch files that can be applied with the "patch" command.
28
What is the difference between "$(( ))" (arithmetic expansion) and a regular variable expansion "$VAR" in bash?
Correct Answer
"$(( expression ))" evaluates the enclosed expression as arithmetic, returning a numeric result for operations like addition, while "$VAR" simply substitutes the literal string value of a variable with no arithmetic
Explanation
Without arithmetic expansion, "$VAR + 1" would be treated as a literal string concatenation in many contexts; "$(( VAR + 1 ))" performs actual integer arithmetic and returns the computed result.
29
What is the purpose of "umask" in Linux?
Correct Answer
It sets a default permission mask that determines which permission bits are removed (masked out) from newly created files and directories
Explanation
The umask value is subtracted from the default permissions (666 for files, 777 for directories) to determine the actual permissions of newly created files/directories — a common umask of 022 results in files created with 644 and directories with 755.
30
What is the difference between "TCP" and "UDP" as they relate to commands like "netstat" or "ss" showing open ports?
Correct Answer
TCP is connection-oriented, establishing a reliable, ordered connection before transfer (visible as states like ESTABLISHED or LISTEN), while UDP is connectionless, so UDP "ports" are just sockets ready to send/receive datagrams without a handshake
Explanation
TCP connections go through states (LISTEN, ESTABLISHED, etc.) visible in netstat/ss output because of its connection-oriented nature, while UDP sockets simply show as bound/listening since UDP has no formal connection setup or teardown.
31
What is the purpose of "logrotate" in Linux system administration?
Correct Answer
It manages the automatic rotation, compression, and removal of old log files to prevent them from consuming excessive disk space, often run periodically via cron
Explanation
"logrotate" reads configuration files (often in /etc/logrotate.d/) specifying rules for when and how to rotate, compress, and eventually delete log files, helping manage disk usage for applications that continuously write logs.
32
What is the difference between "killall" and "pkill"?
Correct Answer
Both send signals to processes matching a given criterion (rather than a specific PID) — "killall" matches by exact process name, while "pkill" can match using more flexible criteria such as patterns, user, or other process attributes
Explanation
Both commands allow sending signals (default SIGTERM) to multiple processes based on name or pattern matching rather than requiring you to look up individual PIDs first, with "pkill" supporting more advanced matching options (e.g. by user with "-u").
33
What is the purpose of the "tee" command?
Correct Answer
It reads from standard input and writes the output to both standard output and one or more files simultaneously
Explanation
"command | tee output.txt" lets you view a command's output on the terminal while simultaneously saving it to a file, useful for logging while monitoring.
34
What is the difference between "type" and "which" when locating a command?
Correct Answer
"type" reports how a command name would be interpreted by the shell (alias, function, builtin, or external file), while "which" searches $PATH for an external executable matching the name, often missing aliases, functions, and builtins
Explanation
Because "which" only checks $PATH for executables, it can give misleading results for names that are actually shell aliases or functions; "type" correctly reflects what would actually run.
35
What is the purpose of "rsync" and what makes it efficient for synchronizing files?
Correct Answer
"rsync" synchronizes files between locations, locally or over a network, using a delta-transfer algorithm that sends only the differences between source and destination, making repeated syncs of large files much faster than a full copy
Explanation
rsync's delta algorithm compares blocks of the source and destination files and transfers only the changed blocks, which is especially efficient for backups and incremental synchronization over slow networks.
36
What does the "envsubst" or using "$VAR" inside a heredoc accomplish in shell scripting?
Correct Answer
An unquoted heredoc (e.g. "<<EOF ... EOF") allows variable expansion within its body, so "$VAR" is replaced by its value, while a quoted delimiter (e.g. "<<'EOF'") disables expansion and treats the content literally
Explanation
This distinction is useful when generating configuration files from templates: an unquoted heredoc lets you substitute shell variables into the output, while a quoted one preserves literal "$" characters (e.g. for scripts containing their own variables).
37
What is the purpose of "/etc/hosts" and how does it interact with DNS lookups?
Correct Answer
"/etc/hosts" is a local file that maps hostnames to IP addresses and is typically checked before querying DNS servers, allowing administrators to override DNS resolution for specific hosts or define local-only hostnames
Explanation
Entries in "/etc/hosts" (e.g. "127.0.0.1 myapp.local") let developers map custom hostnames to specific IPs for local testing without needing actual DNS records, and (depending on nsswitch.conf ordering) usually take precedence over DNS.
38
What is the purpose of "watch" command, e.g. "watch -n 2 df -h"?
Correct Answer
It repeatedly executes a given command at a specified interval (in seconds) and displays the output full-screen, refreshing each time, useful for monitoring changing data
Explanation
"watch -n 2 df -h" re-runs "df -h" every 2 seconds and displays the updated output in place, making it convenient for monitoring resources like disk space or process lists in real time.
39
What is the significance of the "PATH" variable order, and what security risk can arise from including "." (current directory) in it?
Correct Answer
The shell searches $PATH directories in order and runs the first matching executable; including "." (especially early) in $PATH is risky, as it could run a malicious script in the current directory sharing a common command's name instead
Explanation
This is a classic privilege-escalation vector: if an attacker can place a file named "ls" (or similar) in a directory a privileged user will "cd" into, and "." appears early in that user's $PATH, running "ls" could execute the attacker's script instead of /bin/ls.
40
What is the difference between "wget" and "curl" for downloading files from the command line?
Correct Answer
Both can download files over HTTP/HTTPS/FTP, but "curl" is built on libcurl and favored for flexible API interaction with detailed request control, while "wget" suits simple, recursive file or website downloads with retry and mirroring
Explanation
In practice, "curl" is favored for scripting API requests (custom headers, methods, output piping), while "wget" is favored for straightforward downloads, especially recursive website mirroring with "-r".
1
How does the Linux kernel's "Out-Of-Memory (OOM) killer" decide which process to terminate when the system runs critically low on memory?
Correct Answer
The OOM killer calculates a "badness" score for each process, influenced by memory usage and the "oom_score_adj" value, then terminates the highest-scoring process to free memory while minimizing overall damage
Explanation
The OOM killer uses heuristics (a "badness" score based on memory consumption, runtime, and adjustable "oom_score_adj" values) to select a victim process when memory is critically low, aiming to reclaim memory while limiting the impact on the system.
2
What is the difference between a "zombie" process and an "orphan" process?
Correct Answer
A zombie has completed execution but still has a process table entry because its parent has not yet read (reaped) its exit status; an orphan is a process whose parent terminated first, causing it to be re-parented, typically to init/PID 1
Explanation
Zombies are "dead" processes awaiting their exit status to be collected via wait()/waitpid() by their parent — they consume a process table entry (PID) but no other resources; orphans continue running normally but are adopted by init (or a subreaper) when their original parent exits.
3
How do "inodes" relate to files in a Linux filesystem, and what happens to an inode when a file is deleted while a process still has it open?
Correct Answer
An inode stores a file's metadata (permissions, owner, size, data block pointers) separately from its name; deleting a file removes the name-to-inode link, but if a process still has it open, the inode and data remain until that descriptor is closed
Explanation
This behavior (data persisting after "deletion" while a file descriptor remains open) explains why deleting a large log file might not immediately free disk space until the process writing to it is restarted — the data blocks are only released when the link count and open file descriptor count both reach zero.
4
What is the purpose of "namespaces" in the Linux kernel, and how do they relate to containerization technologies like Docker?
Correct Answer
Namespaces partition kernel resources, such as process IDs, network interfaces, mount points, and hostnames, so a group of processes sees its own isolated view of them — a foundational mechanism containers use for isolation without full virtualization
Explanation
Linux namespaces (PID, NET, MNT, UTS, IPC, USER, etc.) allow groups of processes to have isolated views of system resources; combined with cgroups (for resource limiting), they form the kernel-level foundation that container runtimes like Docker build upon.
5
What is the purpose of "cgroups" (control groups) in the Linux kernel?
Correct Answer
Cgroups allow the kernel to limit, account for, and isolate the resource usage (CPU, memory, disk I/O, network, etc.) of a collection of processes, forming the other major kernel mechanism (alongside namespaces) underlying container resource management
Explanation
Cgroups let administrators (or container runtimes) constrain how much CPU, memory, or I/O a group of processes can consume, preventing one set of processes from starving others of resources — a critical feature for multi-tenant systems and containers.
6
What is "copy-on-write" (COW) in the context of the "fork()" system call, and why is it important for performance?
Correct Answer
When fork() is called, the child initially shares the parent's physical memory pages, marked read-only; only when either process writes to a shared page does the kernel copy it, deferring or avoiding the cost of duplicating the address space
Explanation
COW makes fork() efficient: since many forked processes immediately call exec() (replacing their memory entirely) or only read from inherited memory, avoiding an eager full copy of the parent's address space saves significant time and memory in the common case.
7
What is the significance of the "setuid" bit on an executable file, and what security risks does it introduce?
Correct Answer
When set on an executable, the setuid bit runs the program with the file owner's privileges rather than the launching user's — this lets tools like "passwd" modify a root-owned file, but bugs in such programs risk attackers gaining elevated privileges
Explanation
Setuid binaries (like /usr/bin/passwd, owned by root with the setuid bit set) temporarily elevate the executing user's privileges to the file owner's for that program's execution, which is powerful but risky — vulnerabilities in setuid programs are prime privilege-escalation targets.
8
How does "bash" determine command precedence when a command name matches both an alias, a function, a builtin, and an executable in $PATH?
Correct Answer
Bash resolves names in this order: aliases (if interactive, unquoted), then functions, then shell builtins, and finally external executables found via $PATH; this can be bypassed using "command", "\name", or quoting to skip aliases
Explanation
Understanding this precedence explains common gotchas — e.g. why "\ls" or "command ls" bypasses an alias for "ls", and why defining a shell function named after a common command can shadow the actual executable unless explicitly invoked with its full path.
9
What is the purpose of "ulimit" in bash, and how does it relate to per-process resource limits enforced by the kernel?
Correct Answer
"ulimit" is a shell builtin that gets and sets resource limits, such as max file descriptors, processes, or core dump size, for the current shell and its children, enforced by the kernel via setrlimit()/getrlimit() to prevent runaway resource use
Explanation
Resource limits set by "ulimit" (soft and hard limits) are enforced by the kernel for the shell and its child processes — common uses include raising the open file descriptor limit ("ulimit -n") for high-concurrency applications like database servers.
10
What is the difference between "strace" and "ltrace", and what kind of debugging information does each provide?
Correct Answer
"strace" traces system calls and signals made by a process, showing its interactions with the kernel, while "ltrace" traces calls to dynamic library functions — both help diagnose issues without modifying or recompiling the program
Explanation
Both are dynamic tracing tools useful for debugging: "strace" reveals the boundary between a program and the kernel (e.g. why a file open() is failing with a particular errno), while "ltrace" reveals calls into shared libraries like libc.
11
What is the significance of the "noexec", "nosuid", and "nodev" mount options on a filesystem (e.g. for /tmp)?
Correct Answer
"noexec" blocks running binaries from that filesystem, "nosuid" disables setuid/setgid bits there, and "nodev" stops device files there being treated as such — together reducing the risk of privilege escalation via that mount
Explanation
Mounting world-writable directories like /tmp with "noexec,nosuid,nodev" is a common hardening technique, since it limits what an attacker who can write files there can actually do (e.g. they cannot directly execute an uploaded malicious binary from that mount).
12
How does "bash" perform word splitting and globbing, and in what order are these (along with other expansions) typically applied to a command line?
Correct Answer
Bash applies expansions in order: brace, tilde, then parameter/command/arithmetic left-to-right, then word splitting on $IFS, then globbing and quote removal — explaining why unquoted vars with spaces or wildcards behave oddly
Explanation
This expansion order is why "for f in $files" (unquoted) can break if a filename contains spaces (word splitting kicks in) or special glob characters (globbing expands them), while "for f in "$files"" with proper quoting and array usage avoids these pitfalls.
13
What is the purpose of the "/proc" virtual filesystem, and how might it be used to inspect a running process's open file descriptors?
Correct Answer
"/proc" is a virtual filesystem exposing kernel and process info as files, with no data stored on disk; for PID 1234, "/proc/1234/fd/" contains symlinks for each open file descriptor, pointing to the actual files, sockets, or pipes referenced
Explanation
"/proc" provides a live, kernel-generated view into system and process state; "ls -l /proc/<pid>/fd/" is a common technique to see what files, sockets, or pipes a process currently has open, useful for debugging file descriptor leaks.
14
What is the difference between "SIGTERM" and "SIGKILL", and why might a process fail to terminate even when sent SIGKILL?
Correct Answer
SIGTERM is a "polite" request a process can catch to clean up before exiting, while SIGKILL cannot be caught — yet a process can seem "stuck" after SIGKILL if in an uninterruptible kernel state, since the signal applies only on return to user space
Explanation
Processes stuck in uninterruptible sleep (state "D" in "ps", often due to NFS or hardware I/O issues) cannot immediately respond to any signal, including SIGKILL, because the kernel won't deliver signals until the blocking kernel-space operation completes or times out.
15
What is the purpose of "LD_PRELOAD", and what security implications does it have?
Correct Answer
"LD_PRELOAD" specifies shared libraries to load before all others when a dynamic program starts, letting their functions override same-named ones in standard libraries — useful for debugging, but abusable to inject malicious code, as some rootkits do
Explanation
By preloading a shared library, its functions take precedence over those in libraries loaded later (like libc), enabling function interception/hooking — legitimately used for tools like profilers, but also a known technique for userland rootkits to hide malicious activity.
16
How does the Linux page cache improve filesystem read/write performance, and what is the significance of commands like "sync" or the "fsync()" system call?
Correct Answer
The page cache stores recently used disk blocks in RAM so reads come from memory, and writes are often buffered as "dirty" pages before flushing; "sync" and "fsync()" force pending writes to disk, important for durability before shutdown
Explanation
Without understanding the page cache, one might assume "free -h" showing low "free" memory indicates a problem — much of that memory is actually cache that can be reclaimed; "sync"/"fsync" matter for ensuring data durability since writes may otherwise sit in memory ("dirty" pages) for a while before being flushed.
17
What is the purpose of "systemd" units and targets, and how do they differ from traditional SysV init scripts?
Correct Answer
Systemd manages services, devices, and mounts as declarative "unit" files (.service, .mount, .target), with dependency-based parallel startup, socket activation, and supervision — unlike SysV init's sequential scripts run in a fixed runlevel order
Explanation
Systemd's unit-based, dependency-aware, and parallelized approach (along with features like automatic service restart and socket activation) generally allows faster boot times and more robust service management compared to the largely sequential SysV init model.
18
What is "kernel module" loading (e.g. via "insmod" or "modprobe"), and how does "modprobe" differ from "insmod"?
Correct Answer
Kernel modules are code loaded into the running kernel to add functionality, like drivers, without rebooting; "insmod" loads a module directly without resolving dependencies, while "modprobe" resolves and loads dependents first via a dependency database
Explanation
"modprobe" is generally preferred over "insmod" because it automatically handles module dependencies (loading prerequisite modules first) using data generated by "depmod", reducing the chance of a module failing to load due to missing dependencies.
19
What is "DNS resolution order" as configured by "/etc/nsswitch.conf" and "/etc/resolv.conf", and how do they interact?
Correct Answer
"/etc/nsswitch.conf" sets the order sources like "/etc/hosts" and DNS are consulted for hostname lookups, while "/etc/resolv.conf" configures the actual DNS servers and search domains queried — together determining how "example.com" resolves to an IP
Explanation
A common troubleshooting scenario involves checking "/etc/nsswitch.conf" to see if "hosts: files dns" means /etc/hosts entries take precedence over DNS, and checking "/etc/resolv.conf" to verify which DNS servers ("nameserver" lines) are actually being queried.
20
What is the significance of "file descriptor leaks" in long-running processes, and how might "lsof" help diagnose them?
Correct Answer
A file descriptor leak happens when a process repeatedly opens files or sockets without closing them, exhausting the descriptor limit and causing "too many open files" errors; "lsof -p <pid>" lists open files, helping reveal the leak's source
Explanation
Diagnosing fd leaks often involves periodically running "lsof -p <pid> | wc -l" to track the count over time, or examining "/proc/<pid>/fd/" to see which specific files or sockets are accumulating, pointing to code paths that fail to close resources.