UNIX MCQ Questions and Answers

1. Which shell built-in redirects both stdout and stderr to the same file, overwriting it?
A) command >file 2>&1
B) command &> file
C) command > file 2>&1
D) command 1>file &2

2. What does exec 3>out.txt do in a bash script?
A) Executes 3>out.txt as a command
B) Opens file descriptor 3 for reading from out.txt
C) Closes file descriptor 3 and deletes out.txt
D) Opens file descriptor 3 for writing to out.txt (creating/truncating it)

3. Which command substitutes all occurrences of “foo” with “bar” only on lines that contain “baz”?
A) sed ‘s/foo/bar/g’ file | grep baz
B) sed ‘/baz/ s/foo/bar/g’ file
C) grep -l baz file | sed ‘s/foo/bar/g’
D) awk ‘/baz/ {gsub(“foo”,”bar”)}1’ file

4. In bash, what is the difference between $* and $@ when quoted (“$*” vs “$@”)?
A) They are identical in all cases
B) $* preserves argument separation; $@ concatenates with IFS
C) “$*” expands all positional parameters as a single word separated by first char of IFS; “$@” expands each parameter as a separate quoted word
D) “$@” removes empty parameters; “$*” keeps them

5. Which find expression finds regular files modified exactly 7 days ago (not more or less)?
A) find . -mtime 7 -type f
B) find . -mtime +6 -mtime -8 -type f
C) find . -type f -mtime 7
D) find . -daystart -mtime 7 -type f

6. Which pipeline safely handles filenames with newlines and spaces when passing many file names to xargs?
A) ls | xargs -I {} rm {}
B) find . -name ‘*.txt’ | xargs rm
C) find . -name ‘*.txt’ -print0 | xargs -0 rm —
D) printf “%s\n” *.txt | xargs -d ‘\n’ rm

7. What is the effect of set -e in a bash script?
A) Turns on verbose execution mode
B) Causes the script to exit immediately if any command returns a non-zero status (with caveats)
C) Disables error checking for commands
D) Sends errors to stderr instead of stdout

8. In awk, which expression prints the number of fields on each input line?
A) awk ‘{print NF}’ file
B) awk ‘{print NF}’ file
C) awk ‘END {print NF}’ file
D) awk ‘{print NR}’ file

9. How do you create a named pipe (FIFO) called mypipe?
A) mkfifo mypipe
B) Both A and C
C) mknod mypipe p
D) ln -s /dev/fifo mypipe

10. Which command shows which process is listening on TCP port 8080?
A) ps aux | grep 8080
B) cat /proc/net/tcp | grep 8080
C) ss -ltnp | grep :8080
D) iptables -L | grep 8080

11. Which chmod sets setuid bit and gives owner execute permission while leaving other permissions unchanged?
A) chmod 4755 file
B) chmod u+s file
C) chmod +s file
D) chmod 6755 file

12. What does ulimit -c unlimited allow?
A) Unlimited CPU usage
B) Unlimited open file descriptors
C) Generation of core dumps of unlimited size
D) Unlimited memory allocation

13. How can you run a command in the background but still see its output in the foreground terminal?
A) command &
B) nohup command &
C) (command &) ; fg will bring it back — but the simplest is to use command & then fg
D) screen command

14. Which is true about hard links?
A) Hard links can link to directories by default
B) Hard links point to the same inode; removing one name doesn’t remove the data until all links are gone
C) Hard links can cross filesystem boundaries
D) Hard links store the original file’s pathname

15. Which shell expansion performs process substitution?
A) $(command)
B) `command`
C) $(<file)
D) <(command) and >(command)

16. How does trap ‘echo bye’ EXIT behave in a bash script?
A) Executes echo when a child process exits
B) Runs echo bye when the shell exits (normal or via exit/uncaught signal that triggers EXIT)
C) Runs on every command exit
D) Only runs when the script finishes successfully (exit 0)

17. Which awk idiom prints lines sorted by a numeric field (field 3)?
A) awk ‘{print $3,$0}’ file | sort -n
B) awk ‘{print}’ file | sort -k3,3n
C) awk ‘BEGIN{getline} {print $3,$0}’ file
D) sort -n file | awk ‘{print $3,$0}’

18. What does nohup do when launching a process?
A) Starts a process with high priority
B) Runs process in background and splits IO into new terminal
C) Ignores SIGHUP for the process and redirects stdout/stderr to nohup.out if needed
D) Clears environment variables for the process

19. Which is a correct method to test if a file descriptor 3 is open in a shell?
A) [ -e /proc/self/fd/3 ]
B) if [ -e /proc/self/fd/3 ]; then echo open; fi (Linux-specific)
C) test -f /dev/fd/3
D) if fdexists 3; then echo open; fi

20. In sed, how do you insert a line “Hello” before every line matching /^#/ ?
A) sed ‘/^#/ a\Hello’ file
B) sed ‘/^#/ i\Hello’ file
C) sed ‘/^#/ iHello’ file
D) sed ‘s/^#/\nHello\n#/g’ file

21. Which file contains user account information such as login shell and home directory on classic UNIX-like systems?
A) /etc/shadow
B) /etc/hosts
C) /etc/passwd
D) /var/log/auth.log

22. In bash, which expansion returns the length of variable var?
A) ${#var}
B) ${#var}
C) $${var%}
D) ${var:length}

23. Which command will replace DOS CRLF line endings with Unix LF in-place for file f?
A) sed -i ‘s/\r$//’ f
B) Both A and C
C) tr -d ‘\r’ < f > f.tmp && mv f.tmp f
D) dos2unix -n f f

24. What is the effect of >&2 appended to a command?
A) Redirects stderr to stdout
B) Redirects command’s stdout to file descriptor 2 (stderr)
C) Closes stderr
D) Creates a new file descriptor 2

25. Which find option prunes the directory ./.git from search?
A) find . -type d -name .git -prune -o -print
B) find . -path ‘./.git’ -prune -o -print
C) find . -exclude .git
D) find . ! -name .git

26. In shell scripting, what does IFS=$’\n’ accomplish?
A) Sets IFS to a space
B) Sets field separator to newline only, preventing word-splitting on spaces and tabs
C) Deletes all whitespace from variables
D) Causes shell to ignore leading/trailing whitespace

27. Which command lists file descriptors of a running process with PID 1234?
A) ls -l /proc/1234/fd
B) Both A and C
C) readlink -f /proc/1234/fd/*
D) lsof -p 1234

28. What does kill -SIGSTOP 5678 do to process 5678?
A) Terminates it immediately
B) Stops/suspends the process (it can be continued with SIGCONT)
C) Causes it to core dump
D) Restarts the process

29. Which command shows the inode number of a file a.txt?
A) ls -l a.txt
B) stat -c %i a.txt
C) Both B and D
D) ls -i a.txt

30. In bash, what does command || true achieve?
A) Aborts script on error
B) Ensures that the pipeline returns zero exit status even if command fails
C) Runs true only if command succeeds
D) Pipes the output of command to true

31. Which grep option interprets the pattern as a Perl-compatible regular expression?
A) -E
B) -P
C) -F
D) -G

32. How to append output of a command to a file but keep stderr on the terminal?
A) cmd >> file 2>&1
B) cmd >> file 2> /dev/stderr (shell-dependent)
C) cmd 1>>file 2>/dev/tty
D) cmd &>> file

33. In awk, what does gsub(/a/,”b”) do?
A) Replaces first occurrence per line
B) Replaces all occurrences of regex /a/ with “b” in the current record
C) Global substitution across file only at END
D) Substitutes only if field separator is default

34. Which shell construct creates a subshell?
A) { commands; }
B) function foo { commands; }
C) ( commands )
D) while true; do commands; done

35. What is the purpose of ldd on a UNIX system?
A) Lists directories in PATH
B) Displays disk usage
C) Shows shared library dependencies of a binary
D) Dumps kernel logs

36. Which command safely edits a file file.txt in-place using awk (keeping a backup)?
A) awk ‘{…}’ file.txt > file.txt
B) awk -i inplace ‘{…}’ file.txt
C) awk ‘{…}’ file.txt > file.txt.bak && mv file.txt.bak file.txt
D) sed -i.bak ‘expr’ file.txt

37. Which of the following increments a variable i in bash reliably even when i is large?
A) i=$((i+1))
B) let i++
C) Both A and B
D) expr $i + 1

38. Which is true about soft vs hard links across filesystems?
A) Both can cross filesystem boundaries
B) Soft (symbolic) links can cross filesystems; hard links cannot
C) Hard links are always faster than soft links
D) Symbolic links share inode with target

39. How do you preserve environment variables when using su to switch user?
A) su – user
B) su user
C) su -m user or su –preserve-environment user (depends on su implementation)
D) sudo -i user

40. Which bash option prevents globbing (filename expansion)?
A) set -f disables globbing
B) set -f
C) set -u
D) set -n

41. Which command displays kernel ring buffer messages?
A) dmesg
B) dmesg
C) journalctl -k
D) kernlog

42. To run commands with a limited set of file descriptors and then replace the shell with another process, which built-in is helpful?
A) exec
B) exec
C) env
D) setsid

43. What is the purpose of /dev/null?
A) A file storing logs
B) A black hole device that discards all data written and returns EOF on read
C) A swap file used by kernel
D) A device for null-initialized memory

44. Which command will show parent process tree up to init for the current shell?
A) ps -ef
B) pstree -s $$
C) pstree -s $$
D) pgrep -P $$

45. In a Makefile, what does .PHONY indicate?
A) A variable name
B) Targets that should be executed regardless of the presence of files with the same name
C) Default target to run
D) A special macro for concurrency

46. Which signal number usually corresponds to SIGTERM on a POSIX system?
A) 9
B) 15
C) 2
D) 1

47. Which command prints the first 10 lines of a file?
A) tail -n 10 file
B) head file (alias for head -n 10)
C) sed -n 1,10p file
D) awk ‘NR<=10’ file

48. How do you run a command with higher scheduling priority (lower nice value) as a privileged user?
A) nice -n -10 cmd
B) renice -n -10 -p PID or nice -n -10 cmd as root
C) schedtool -n -10 cmd
D) ionice -n -10 cmd

49. Which shell redirection makes a heredoc treat tabs as ignored indentation markers (<<-)?
A) <<EOF
B) <<~EOF
C) <<-EOF
D) <<<EOF

50. In sed, how would you print only lines between patterns start and end inclusive?
A) sed -n ‘/start/,/end/p’ file
B) sed -n ‘/start/,/end/p’ file
C) awk ‘/start/{f=1} f; /end/{f=0}’ file
D) Both A and C (both are valid)

51. What does strace -f -o trace.txt ./program accomplish?
A) Traces only the main process system calls
B) Traces system calls of program and its children (-f) and writes to trace.txt (-o)
C) Profiles CPU usage to trace.txt
D) Generates a source-level debug trace

52. Which of the following is true about the superblock in a filesystem?
A) It stores user permissions only
B) It contains filesystem metadata (size, block size, free blocks, inode counts) and is critical to mount
C) It is stored on a remote server for distributed FS
D) It contains file contents

53. How do you create an anonymous temporary file that is removed when closed in shell?
A) mktemp then rm it
B) Use mktemp to create and open a descriptor, or in bash use exec 3> >(cat > “$(mktemp)”) — common approach: tmp=$(mktemp) and trap to remove it
C) touch /tmp/foo && rm /tmp/foo
D) mkfifo

54. Which rsync option preserves symbolic links as links (not dereferencing them)?
A) -L
B) -l
C) -a alone does not preserve symlinks
D) –copy-links

55. What does basename /usr/local/bin/script.sh .sh output?
A) /usr/local/bin/script
B) script.sh
C) script
D) bin/script

56. Which of these is true about the process init (or systemd) with PID 1?
A) It can be killed by normal users
B) It is the ancestor of all processes and adopts orphaned processes
C) It runs in user space only for login shells
D) It never reaps zombies

57. Which command modifies the access control list (ACL) to grant user alice read permission on file?
A) chmod u+r file
B) setfacl -m u:alice:r– file
C) chown alice file
D) aclmod alice +r file

58. In shell, which construct will treat pattern as a glob pattern for matching a string variable $s?
A) if [[ $s = pattern ]]
B) if [[ $s == pattern ]] (within [[ ]], == supports globbing)
C) if [ $s = pattern ]
D) if test $s -gl pattern

59. What does git use to store contents internally in the .git/objects directory?
A) Plain text copies of files
B) Compressed objects keyed by SHA-1/SHA-256 (blobs, trees, commits)
C) Full backups of working tree only
D) Executable images of history

60. Which of the following finds files with setuid bit set?
A) find / -perm /4000
B) find / -perm -4000
C) find / -type f -perm -4000
D) find / -setuid

61. Which pipeline safely counts unique IP addresses in an Apache access log using awk and sort?
A) awk ‘{print $1}’ access.log | sort | uniq -c | sort -nr
B) awk ‘{print $1}’ access.log | sort -u | wc -l (counts uniques)
C) cut -d’ ‘ -f1 access.log | sort | uniq
D) grep -oE ‘([0-9]+\.){3}[0-9]+’ access.log | sort | uniq -c

62. In bash, how does read -r differ from read?
A) -r reads raw file descriptors only
B) -r disables backslash escaping, so backslashes are not treated specially
C) -r reads in raw bytes including nulls
D) -r reads until carriage return only

63. What is the difference between > and |& in bash?
A) > pipes both stdout and stderr; |& redirects to a file
B) > redirects stdout to a file; |& pipes both stdout and stderr to the next command
C) |& is deprecated > replacement
D) No difference

64. Which command will follow a file as it grows and show timestamps?
A) tail -f file
B) tail -F file
C) tail -f –pid=$(pgrep prog) file (for following with pid)
D) tail -f file | ts (with ts from moreutils shows timestamps)

65. Which shell feature allows you to run commands in a different environment without exporting variables?
A) env VAR=val command
B) VAR=val command
C) export VAR=val; command
D) source .env; command

66. How can you make a bash function localize variables so they don’t pollute global scope?
A) function foo { var=1; }
B) function foo { local var=1; }
C) var=1; declare -g var
D) let var=1

67. Which command will show file access time (atime) for file?
A) ls -l file
B) stat file
C) stat -c %x file (access time)
D) date –reference=file

68. Which option to tar creates a gzipped archive?
A) tar -cf
B) tar -czf
C) tar -xzf
D) tar -tf

69. What is the effect of chroot?
A) Changes current working directory
B) Changes root directory for a process, restricting its view of the filesystem
C) Returns a process to init namespace
D) Elevates process privileges to root

70. Which sed command deletes lines that contain only whitespace?
A) sed ‘/^$/d’
B) sed ‘/^[[:space:]]*$/d’
C) sed ‘/\s/d’
D) sed -n ‘/\S/p’

71. Which of these best describes an inode?
A) The file’s human-readable name and path
B) A filesystem data structure that stores metadata about a file (permissions, owner, timestamps, block pointers), not the file name
C) A kernel process that manages files
D) A special device file for network sockets

72. How does cron differ from at?
A) cron runs jobs once only; at schedules recurring jobs
B) cron schedules recurring jobs based on a timetable; at schedules one-time jobs
C) at is deprecated on UNIX
D) cron requires root privileges only

73. In shell, what does >&- do?
A) Redirects stdout to closed descriptor
B) Closes the current stdout (or specified) file descriptor
C) Redirects stderr to null
D) Duplicates stdout to stdin

74. Which tool can show which library function calls a process makes at runtime in user-space (not system calls)?
A) strace
B) ltrace
C) gdb
D) perf

75. How to safely remove all files owned by user bob under /var/tmp?
A) rm -rf /var/tmp/*
B) find /var/tmp -user bob -exec rm -rf — {} +
C) find /var/tmp -name bob -delete
D) chown -R root /var/tmp && rm -rf /var/tmp/*

76. Which bash option treats unset variables as an error when substituting?
A) set -e
B) set -u (or set -o nounset)
C) set -o errexit
D) set -x

77. What is the primary difference between a pipe (|) and a socket?
A) Both are the same at kernel level
B) A pipe is unidirectional and exists between related processes; a socket is bidirectional and can be used between unrelated processes or across the network
C) Pipes are for files only; sockets for network only
D) Sockets cannot be used for inter-process communication on the same host

78. Which command will atomically replace a file target with file tmp?
A) mv tmp target
B) cp tmp target
C) mv tmp target (assuming same filesystem; rename is atomic within FS)
D) cat tmp > target

79. In shell scripting, what does printf ‘%s\n’ “$var” do compared to echo “$var”?
A) No difference at all
B) printf is more portable and predictable (no interpretation of backslashes or options), while echo behavior varies
C) printf adds spaces between args by default
D) echo is safer for arbitrary strings

80. Which of the following is appropriate to debug a bash script to show each command before execution?
A) bash -v script.sh
B) bash -x script.sh
C) set -u script.sh
D) sh -n script.sh

81. What is the purpose of the LD_LIBRARY_PATH environment variable?
A) Stores path for executables
B) Specifies runtime search path for shared libraries before default locations
C) Used by linker at compile time only
D) Security variable for loader restrictions

82. Which of these commands will print the absolute path of the current working directory?
A) pwd -P
B) pwd
C) Both A and B (but pwd -P resolves symlinks to physical dir)
D) readlink -f .

83. How do you prevent a command from being hashed by bash (so it re-searches PATH each invocation)?
A) hash -r
B) hash -d cmd (to delete specific hashed entry)
C) unset PATH
D) command -v cmd

84. Which awk variable holds the current record separator?
A) RS
B) RS
C) FS
D) ORS

85. Which of the following removes directory if empty, and errors if not empty?
A) rm -r dir
B) rmdir dir
C) rmdir dir
D) rm dir

86. How do you test if a process with PID 9999 is running without sending signals?
A) kill -0 9999
B) kill -0 9999 (returns 0 if process exists and you have permission)
C) ps -p 9999 -o pid=
D) test -e /proc/9999

87. Which file descriptor numbers correspond to stdin, stdout, and stderr?
A) 0, 1, 2
B) 0, 1, 2
C) 1, 2, 3
D) 2, 1, 0

88. What is the effect of umask 027?
A) Files created will have permissions 750 by default
B) New files will prohibit group write and all permissions for others; numerical effect: subtract 027 from default creation mode
C) Sets default owner to root
D) Sets date mask for logs

89. Which is the correct way to combine a multi-line variable into an array of lines in bash?
A) arr=($var)
B) IFS=$’\n’ read -r -d ” -a arr <<< “$var” (one correct robust method)
C) arr=(“${var}”)
D) arr=($(echo “$var”))

90. Which of the following will cause a pipeline to have the exit status of the last failed command in bash (with set -o pipefail disabled by default)?
A) cmd1 | cmd2; echo $? returns status of cmd2 by default
B) Enabling set -o pipefail makes pipeline return status of rightmost non-zero exit
C) set -e changes pipeline status semantics
D) pipefail is not a real option

91. Which system concept ensures that modifications to a file are not lost on crash by committing metadata and data in specific order?
A) Journaling filesystem
B) Journaling filesystem (metadata journaling or full-data journaling depending on mode)
C) Copy-on-write only
D) RAID mirroring

92. How to run commands as another user using sudo and preserve environment variable FOO?
A) sudo -u bob FOO=bar cmd
B) sudo –preserve-env=FOO -u bob cmd
C) sudo su – bob; FOO=bar; cmd
D) sudo env FOO=bar -u bob cmd

93. Which perl-compatible one-liner prints the 5th column of whitespace-separated input?
A) perl -lane ‘print $F[4]’
B) perl -lane ‘print $F[4]’
C) awk ‘{print $5}’
D) cut -d’ ‘ -f5

94. When a process is in ‘D’ state (in ps output), what does it signify?
A) Stopped (SIGSTOP)
B) Uninterruptible sleep (usually IO wait)
C) Zombie process
D) Idle kernel thread

95. Which command edits the current shell’s PATH to add /opt/bin at beginning persistently for the session?
A) PATH=$PATH:/opt/bin
B) PATH=/opt/bin:$PATH; export PATH
C) export PATH PATH=/opt/bin:$PATH
D) set PATH /opt/bin:$PATH

96. How do you check which file a shared library libfoo.so resolves to at runtime for a binary prog?
A) ldd prog | grep libfoo
B) ldd prog | grep libfoo
C) objdump -p prog
D) readelf -d prog

97. Which command truncates a file log.txt to zero length without changing inode?
A) rm log.txt && touch log.txt (changes inode)
B) > log.txt
C) : > log.txt or > log.txt (both truncate in-place)
D) truncate -s 0 log.txt (also correct)

98. Which of these is true about POSIX pipes and atomicity?
A) Writes of any size are atomic to a pipe
B) Writes of size less than PIPE_BUF are atomic to a pipe; larger writes may interleave
C) All writes are serialized by kernel always
D) Pipe atomicity is undefined

99. Which command shows open files by all processes, helpful to find who has deleted a file but still holds it open?
A) lsof | grep deleted
B) lsof +L1 (lists open files with link count <1)
C) fuser -v
D) stat /proc/*/fd

100. Which shell pattern matches filenames starting with “data” and ending with a number, like data1, data23?
A) data*
B) data[0-9]
C) data[0-9]*
D) data([0-9])+