Unlock hundreds more features
Save your Quiz to the Dashboard
View and Export Results
Use AI to Create Quizzes and Analyse Results

Sign inSign in with Facebook
Sign inSign in with Google

Shell Scripting Interview Quiz: Test Your Skills Now

Think you can ace this shell scripting quiz? Test bash script skills and tackle Unix shell scripting interview questions!

Difficulty: Moderate
2-5mins
Learning OutcomesCheat Sheet
Paper art illustration of shell script terminal window, code snippet, quiz checkmarks on golden yellow background

This shell scripting quiz helps you prep for interviews by practicing bash syntax, Unix shell tools, and real tasks. Answer practical items on variables, loops, pipes, files, and exit codes; get a score and quick feedback so you can spot gaps before the big day.

What is the purpose of the shebang (#!) line at the beginning of a shell script?
It indicates that the following lines are configuration options.
It tells the system which interpreter to use to execute the script.
It serves as a comment and is ignored by the shell.
It sets the file's permission to executable.
The shebang (#!) at the start of a script tells the operating system which interpreter should run the file. Without it, users must invoke the interpreter explicitly. This mechanism is recognized by Unix-like kernels and is essential for portability.
How do you make a shell script executable?
Add 'executable: true' in the script header
touch script.sh
chmod 644 script.sh
chmod +x script.sh
The chmod +x command adds execute permissions to the script file, allowing it to be run directly. Other permissions like 644 do not include the execute bit. The touch command only updates timestamps.
Which symbol is used to reference a variable in bash scripts?
#
$
%
@
In bash scripting, variables are referenced by prefixing their name with a dollar sign ($). For example, $VAR retrieves the value of VAR. Other symbols like # or @ have different meanings in bash.
How can you comment a single line in a bash script?
Wrap the line in /* */
Prefix the line with --
Prefix the line with //
Prefix the line with #
Single-line comments in bash begin with a hash (#). The shell ignores any text following # on the same line. Other comment styles like // or /* */ are used in other languages, not bash.
What command lists files and directories in the current directory?
dir
ls
list
show
The ls command lists the contents of a directory in Unix-like systems. While dir works in some shells, ls is the standard, POSIX-defined command. Commands like list or show do not exist by default.
Which symbol is used to redirect standard output to a file, overwriting its contents?
>>
&>
<
>
The > operator redirects standard output to a file, replacing its contents. The >> operator appends instead. The < operator redirects input, and &> redirects both stdout and stderr in some shells.
What is the exit status of a successful command in Unix?
1
255
-1
0
In Unix and Linux, a process returns an exit status of 0 to indicate success. Non-zero values indicate different types of errors. This convention is used by shells to manage control flow.
How do you execute a script named script.sh in the current directory while respecting its shebang?
./script.sh
sh script.sh
source script.sh
bash script.sh
Using ./script.sh runs the file as an executable, invoking its shebang interpreter. Calling sh or bash explicitly may ignore the shebang or use a different shell. source (or .) runs the script in the current shell environment.
How do you correctly define a function named myfunc in bash?
def myfunc() { }
myfunc() { commands; }
function myfunc { commands; }
function myfunc commands end
In bash, a function is defined by name followed by () and a block of commands in braces. The syntax function myfunc { ... } without parentheses is also allowed in some shells but not POSIX-compliant. Keywords like def are not valid in bash. Bash functions
How can you access the third command-line argument passed to a bash script?
$3
$argc[3]
%3
$args[2]
Bash uses positional parameters: $1, $2, $3, etc., to represent the first, second, third arguments. There is no array named argc or args for this purpose. The % symbol has no special meaning in this context.
Which test expression checks if two strings are equal in a bash conditional?
[ "$a" -eq "$b" ]
[ "$a" != "$b" ]
[ $a == $b ]
[ "$a" = "$b" ]
Within single-bracket test ([ ]), = is used for string comparison. -eq is for integer comparison, == may work in [[ ]] but not in POSIX [, and != tests inequality. Quoting protects against word splitting.
What is the effect of set -e at the start of a bash script?
Disable all error checking and continue execution.
Exit the script if any command returns a non-zero status.
Enable verbose mode, printing each command before execution.
Treat unset variables as errors and exit.
The -e option causes bash to exit immediately if any command fails (returns a non-zero exit code). This helps catch errors early. Verbose mode is -v, and treating unset variables is -u.
How can you read a line of user input into a variable named name in bash?
scan name
gets name
input name
read name
The read builtin reads a line from standard input and assigns it to the specified variable. Commands like scan or input do not exist in bash.
What will echo $((5 + 3)) output in bash?
$((5 + 3))
53
5+3
8
The $(( )) syntax performs arithmetic expansion in bash, evaluating the expression inside. 5 + 3 equals 8. Other forms just output the literal string or concatenate.
Which operator appends output to a file rather than overwriting it?
>>
>&
<
>
The >> operator appends standard output to the specified file. The > operator truncates or creates the file before writing. < is for input redirection. &> redirects both stdout and stderr in bash.
How do you check if a file named data.txt exists in bash?
[ -r data.txt ]
[ -d data.txt ]
[ -f data.txt ]
[ -z data.txt ]
In bash test expressions, -f checks if the file exists and is a regular file. -d checks for a directory, -r tests readability, and -z checks for zero-length strings.
How can you get the number of elements in a bash array named arr?
${#arr[*]}
${#arr[@]}
${arr.length}
${#arr}
In bash, ${#array[@]} returns the number of elements in the array. ${#array[*]} behaves similarly but can differ when quoted. ${#arr} gives the length of the first element, and arr.length is not valid syntax.
Which built-in helps you parse command-line options in bash scripts?
getopt
optparse
getopts
parseopts
getopts is the POSIX-compliant bash builtin for parsing short command-line options. getopt is an external program and less portable. Bash has no optparse or parseopts builtins.
What is the preferred method for arithmetic expansion in bash?
let a + b
$[a + b]
`expr $a + $b`
$((a + b))
The $(( )) syntax is the modern and preferred way to perform arithmetic expansion in bash. expr is an older external command, $[ ] is deprecated, and let is a builtin but less flexible.
What does process substitution <(...) do in bash?
Provides the output of a process as if it were a file.
Executes a command in the background without output.
Redirects both stdout and stderr to a file.
Substitutes environment variables into a command.
Process substitution <(command) allows a command's output to be treated as a file, which can be read by other programs. It uses named pipes or /dev/fd entries under the hood. This is useful for diff, grep, or other tools that expect filenames.
How do you prevent word splitting and globbing when expanding a variable in bash?
Set IFS to an empty string permanently.
Escape each space with backslashes.
Surround the expansion with double quotes, e.g., "$var".
Use single quotes around the variable name, e.g., '$var'.
Double-quoting "$var" prevents bash from splitting the value on whitespace and from pathname expansion. Single quotes literalize the $, not the expansion result. Escaping spaces manually is error-prone, and changing IFS affects parsing globally.
How can you include the directory of the running script in PATH within the script itself?
export PATH="$PATH:~"
PATH="$(dirname "$0"):$PATH"
cd $(dirname $0)
PATH="$PWD:$PATH"
$(dirname "$0") evaluates to the directory of the running script, which can then be prepended to PATH. Using PWD only gives the current working directory, not the script's location. cd changes directories but doesn't modify PATH.
Given IFS=',', how can you split a comma-separated line into an array named fields?
fields=(${line//,/ })
read fields -d ',' "$line"
split -t, line
IFS=',' read -ra fields <<< "$line"
Setting IFS=',' and using read -ra reads the input record into the fields array, splitting on commas. The here-string <<< passes the variable content as stdin. Other methods are either external or incorrect syntax.
What is the purpose of trap "rm /tmp/tempfile" EXIT in a bash script?
Set a signal handler only for SIGTERM.
Ensure the specified command runs when the script exits, regardless of termination method.
Cause the script to exit immediately.
Trap the EXIT command and ignore it.
trap ... EXIT registers a handler that executes when the script exits for any reason, including errors or interrupts. This is useful for cleanup tasks. It does not ignore EXIT, nor does it target only SIGTERM.
How can you create a name reference (nameref) variable in bash to reference another variable?
ref=&orig
link ref orig
declare -n ref=orig
declare ref=orig -r
Namerefs are created in bash using declare -n name=other, which makes 'name' refer to the variable 'other'. This allows indirect variable manipulation. Other forms like &orig or link are not valid.
0
{"name":"What is the purpose of the shebang (#!) line at the beginning of a shell script?", "url":"https://www.quiz-maker.com/QPREVIEW","txt":"What is the purpose of the shebang (#!) line at the beginning of a shell script?, How do you make a shell script executable?, Which symbol is used to reference a variable in bash scripts?","img":"https://www.quiz-maker.com/3012/images/ogquiz.png"}

Study Outcomes

  1. Understand Shell Scripting Fundamentals -

    Grasp core concepts and syntax of bash scripts, enabling you to confidently address shell scripting questions for interviews and real-world tasks.

  2. Apply Essential Bash Commands -

    Execute and combine common bash commands effectively to solve practical exercises and shell scripting quiz challenges with accuracy.

  3. Analyze Unix Shell Scripting Logic -

    Break down complex shell scripts into logical steps, ensuring you can interpret interview questions for Unix shell scripting and craft correct solutions.

  4. Troubleshoot and Debug Scripts -

    Identify and resolve common errors and pitfalls in shell scripts, boosting your confidence when facing test bash script questions.

  5. Optimize Scripting Performance -

    Implement best practices to streamline script execution, improving efficiency and demonstrating advanced skills during interviews.

  6. Evaluate Interview Readiness -

    Assess your mastery through instant feedback and targeted scoring, preparing you to ace your next shell scripting interview quiz.

Cheat Sheet

  1. Parameter Expansion Mastery -

    Understanding constructs like ${var:-default}, ${var#prefix}, and ${#var} lets you manage defaults, trim patterns, and calculate string lengths without external tools. For example, ${filename%.txt} removes a .txt suffix efficiently (GNU Bash Manual). Use the mnemonic "PDL" (Parameter, Default, Length) to recall core expansions.

  2. Control Structures & Exit Statuses -

    Mastering if-elif-else, case statements, and loops (for, while, until) ensures clean logic and robust flow control (POSIX Shell Command Language). Remember that every command returns an exit status (0 for success, nonzero for failure) and combine commands with && and || for concise branching. Practice a sample: if [ -f "$file" ]; then echo "Exists"; fi.

  3. File Tests & I/O Redirection -

    Knowing file-condition operators like -f (regular file), -d (directory), and -r (readable) lets you validate inputs before processing (The Linux Documentation Project). Combine >, >>, 2>&1 to redirect stdout and stderr - e.g., script.sh >out.log 2>&1. A helpful mnemonic is "one handles output, two handles errors."

  4. Functions & Modular Scripting -

    Defining reusable functions (func_name() { … }) and using local variables improves readability and reduces duplication (Bash Reference Manual). For instance, local count=0 inside a function prevents global collisions. Think "divide and conquer" to break complex scripts into small, testable units.

  5. Debugging & Strict Mode -

    Enable safe scripting with set -euo pipefail and optionally -x for tracing - this combo stops on errors, flags unset vars, and catches pipeline failures (Stack Overflow consensus). Remember the catchy "EU P!" - Error, Unset, Pipefail! Debug with PS4='+ ${BASH_SOURCE##*/}:$: ' to pinpoint issues by line.

Powered by: Quiz Maker