---
title: "Bash: Shell Scripting Fundamentals"
description: "Test your knowledge of Bash scripting fundamentals with this comprehensive quiz covering variables, conditionals, loops, functions, I/O redirection, special parameters, and shell scripting best practices."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/quizzes/post/bash-shell-scripting-fundamentals-quiz
---

# Bash: Shell Scripting Fundamentals

Welcome to the Bash Basics Quiz! This quiz is designed to test your understanding of fundamental Bash scripting concepts, syntax, and best practices. Each question is multiple-choice, and you'll find hints to help you along the way. Good luck!

## Questions

### 1. What is the purpose of the "shebang" line (#! /bin/bash) at the top of a script?

- It defines the character encoding for the text file
  - Character encoding is typically handled by the editor or system locales rather than a shebang line.
- **It specifies the interpreter used to execute the script** ✅
  - The shebang tells the kernel which binary to use to parse the commands within the file.
- It grants the current user execution permissions
  - Execution permissions are managed via the chmod command; the shebang is only for interpreter routing.
- It allocates a dedicated block of memory for the process
  - Memory allocation is handled by the kernel at runtime and is not influenced by the shebang line.

**Hint:** It tells the operating system how to read the file.

### 2. How do you correctly assign the value "Alpha" to a variable named "Project"?

- Project = Alpha
  - Spaces around the equals sign cause Bash to interpret the variable name as an external command.
- **Project="Alpha"** ✅
  - Variable assignment in Bash requires that no spaces exist between the name, the operator, and the value.
- $Project="Alpha"
  - The dollar sign is used to expand or reference a variable; it is not used during the initial assignment.
- set Project "Alpha"
  - The set command modifies shell positional parameters or internal options rather than assigning variables.

**Hint:** Bash is extremely sensitive to whitespace around the equals sign.

### 3. What does the variable "$?" represent?

- The Process ID of the currently running script
  - The Process ID of the current shell session is stored in the special variable designated by $$.
- **The exit status of the most recently executed command** ✅
  - This holds an integer (0-255) indicating whether the previous command succeeded or encountered an error.
- The total number of arguments passed to the script
  - The count of positional parameters provided by the user is stored in the special variable $#.
- The name of the script file currently being executed
  - The filename or path used to invoke the script is stored in the first positional parameter, $0.

**Hint:** Success is usually 0.

### 4. Which command is used to accept user input during a script?

- input
  - While common in languages like Python, input is not a standard built-in command in the Bash shell.
- **read** ✅
  - The read command pauses execution to capture a line of text from the standard input stream.
- fetch
  - Fetch is often used for retrieving network resources or system info, not for capturing user keyboard input.
- accept
  - Accept is used in network socket programming; Bash uses read for interactive script data entry.

**Hint:** It "reads" from the standard input.

### 5. How do you check if a variable "VAR" is empty?

- [ -n "$VAR" ]
  - The -n flag checks for a non-zero length, meaning it returns true only if the variable is NOT empty.
- **[ -z "$VAR" ]** ✅
  - The -z flag specifically checks if the string length is zero, returning true for empty variables.
- [ -e "$VAR" ]
  - The -e flag is used in file testing to determine if a specific path exists on the disk.
- [ -v "$VAR" ]
  - The -v flag checks if a variable is set or defined, which is different from checking if its value is empty.

**Hint:** Think "Zero" length.

### 6. Which brackets are preferred in modern Bash for conditional tests?

- `( )`
  - Parentheses are used for grouping commands in subshells rather than performing logical conditional tests.
- **`[[ ]]`** ✅
  - Double brackets are a Bash-specific keyword that offers more robust string and pattern matching than [ ].
- `{ }`
  - Curly braces define code blocks or functions and are used for parameter expansion, not logical tests.
- `< >`
  - Angle brackets are reserved for input/output redirection and process substitution in the shell.

**Hint:** Double is more powerful than single.

### 7. How do you perform integer arithmetic to add 5 and 2?

- result = 5 + 2
  - Bash treats this as a literal string assignment; the variable would contain the text "5 + 2".
- **((result = 5 + 2))** ✅
  - Double parentheses create an arithmetic context where mathematical operations are evaluated and assigned.
- result = $[5 + 2]
  - This is an older, deprecated syntax for arithmetic expansion that is no longer recommended for modern scripts.
- let result 5 + 2
  - The let command requires the expression to be a single argument, usually requiring quotes like let "result=7".

**Hint:** Use the double-parentheses syntax.

### 8. What does the "export" command do?

- Encodes the script into a portable binary format
  - Bash scripts are interpreted text; export does not modify the file format or create binaries.
- **Makes a variable available to child processes** ✅
  - Exporting ensures that any command or script launched from the current shell can access the variable.
- Saves the current shell history to a local file
  - History management is handled by history -w; export is strictly for environment variable scope.
- Transmits the script to a remote network server
  - Network transmission requires tools like scp or rsync; export only affects the local shell environment.

**Hint:** Think about parent and child processes.

### 9. Which loop syntax is correct for iterating through a list of files?

- `foreach file in *.txt`
  - Foreach is valid in other shells like tcsh, but the standard Bash keyword for iteration is "for".
- **`for file in *.txt; do ... done`** ✅
  - The for-in-do-done structure is the standard Bash syntax for iterating over lists and globs.
- `loop file over *.txt { ... }`
  - Bash does not use the "loop" keyword or curly braces for the standard structure of its control loops.
- `while file in *.txt; do ... done`
  - A while loop evaluates a conditional command for truthiness rather than iterating over a list of items.

**Hint:** For item in list...

### 10. What is the difference between single quotes (' ') and double quotes (" ")?

- Single quotes are for paths; double are for text
  - Both quote types can be used for paths or text; the difference is in how they handle special characters.
- **Single quotes are literal; double quotes allow expansion** ✅
  - Single quotes prevent all expansion (like $VAR), while double quotes allow variables to be expanded.
- Double quotes enable mathematical script operations
  - Math is handled by arithmetic expansion $(()) and is independent of the surrounding string quotes.
- Single quotes are required for all shell comments
  - Comments are initiated by the # symbol and are generally not enclosed in quotes at all.

**Hint:** One is literal, one allows expansion.

### 11. How do you capture the output of a command into a variable?

- `VAR = > command`
  - The greater-than symbol redirects command output to a physical file on the disk, not to a variable.
- **`VAR=$(command)`** ✅
  - Command substitution executes the command and assigns its standard output to the specified variable.
- `VAR = {command}`
  - Curly braces are used for parameter expansion or code grouping, not for capturing execution output.
- `VAR << command`
  - The double less-than symbol is used for Here Documents to provide multi-line input to a command.

**Hint:** $(command)

### 12. What does the "break" keyword do in a loop?

- Interrupts the script and triggers an error
  - Break is a controlled flow command used for logic management, not for error reporting or crashing.
- **Exits the loop and continues the script** ✅
  - It terminates the nearest enclosing loop immediately and executes the code following the "done" keyword.
- Restarts the current iteration from the top
  - Restarting or skipping to the next iteration is the specific function of the "continue" keyword.
- Suspends the script for a specified duration
  - Pausing or suspending script execution is the role of the sleep command, not the break keyword.

**Hint:** Exiting the cycle.

### 13. Which special variable contains the number of arguments passed to a script?

- `$@`
  - This variable expands to all the arguments as separate words, not the integer count of those arguments.
- **`$#`** ✅
  - This variable holds the total count of positional parameters that were provided to the script at runtime.
- `$*`
  - This variable expands to all the arguments as a single string, which is useful for logging or echoing.
- `$!`
  - This special variable contains the Process ID of the most recently executed background command.

**Hint:** Think "Count".

### 14. How do you define a function in Bash?

- `def my_func():`
  - This is the standard syntax for Python; Bash functions do not use "def" or trailing colons.
- **`my_func() { ... }`** ✅
  - Functions are defined by a name followed by parentheses and a block of code enclosed in curly braces.
- `function:my_func { ... }`
  - Bash uses a space or parentheses to separate names; the colon is not a valid separator for functions.
- `new func my_func { ... }`
  - The "new" keyword is used in object-oriented languages; Bash is a procedural shell scripting language.

**Hint:** function_name() { ... }

### 15. What is the "exit 1" command typically used for?

- To signal that the script completed successfully
  - A successful completion is traditionally indicated by returning an exit code of 0.
- **To signal that an error occurred during execution** ✅
  - Any non-zero exit code informs the calling environment that the script failed to finish as expected.
- To return the script to the main menu function
  - Exit terminates the entire process; it cannot be used to jump between internal script functions.
- To pause the script until the user clicks a key
  - Pausing for input is the job of the read command; exit stops the script and releases resources.

**Hint:** Ending with an error.

### 16. What does "2>&1" do in a command?

- It runs the command in a dual-core CPU mode
  - CPU affinity is managed by taskset; this syntax is exclusively for handling file descriptors.
- **It merges the error stream into the output stream** ✅
  - This redirects file descriptor 2 (stderr) to the same location as file descriptor 1 (stdout).
- It forces the command to run with root authority
  - Authority is managed by sudo or su; redirection symbols have no effect on process privileges.
- It hides all output from the terminal display
  - To hide output, you must redirect both streams specifically to the /dev/null null device.

**Hint:** Redirecting streams.

### 17. Which comparison operator is used for strings in [[ ]], but NOT for integers?

- `-eq`
  - The -eq operator is reserved for integer comparison and will not work correctly for comparing text strings.
- **`==`** ✅
  - The double equals operator is used for string matching; integers use specific flags like -eq or -lt.
- `-gt`
  - This operator stands for "Greater Than" and is strictly applied to numeric values, not alphabetical order.
- `>`
  - While used for redirection, in a test block it compares string sort order, not integer magnitude.

**Hint:** The equals sign.

### 18. What is a "Here Document" (EOF)?

- A script header that contains author metadata
  - Author metadata is stored in standard comments; Here Documents are for providing command input data.
- **A method for passing multi-line input to a command** ✅
  - It uses the "<<" operator to feed a block of text directly into a command until a delimiter is reached.
- A specific file extension used for shell binaries
  - Shell scripts generally use .sh or no extension; there is no standard "EOF" file extension for binaries.
- A system signal sent when a file is corrupted
  - File corruption is detected by the filesystem or disk tools, not by the Here Document syntax.

**Hint:** Feeding multiple lines of text into a command.

### 19. How do you run a script "backup.sh" in the background?

- `start backup.sh`
  - Start is a Windows-specific command; Bash uses suffix symbols to manage process execution modes.
- **`./backup.sh &`** ✅
  - The trailing ampersand tells the shell to execute the script as a background job in a subshell.
- `run -bg backup.sh`
  - Bash does not utilize a "run" command for backgrounding; it relies on the ampersand syntax.
- `detach backup.sh`
  - Detach is often an option in terminal multiplexers like tmux, but it is not a built-in Bash keyword.

**Hint:** Add a character at the end.

### 20. What does "set -x" do?

- Automatically terminates the script on any error
  - Exiting on error is enabled via "set -e"; the "-x" flag serves a different debugging purpose.
- **Traces and displays each command before execution** ✅
  - This debugging mode prints commands and their expanded arguments to the terminal as they are run.
- Sets the script to run in a read-only shell mode
  - Read-only modes for variables are set via the readonly command, not via a shell execution flag.
- Enables extended regular expressions in the shell
  - Regex capabilities are determined by the command being used (like sed or awk), not by the "set" command.

**Hint:** Debugging.

### 21. Which variable represents all arguments passed to the script as individual quoted items?

- `$*`
  - This variable joins all parameters into a single string, which may lose individual argument boundaries.
- **`$@`** ✅
  - This variable preserves each argument as a separate entity, ensuring spaces within arguments are handled correctly.
- `$#`
  - This represents the total count of the arguments provided, rather than the content of the arguments themselves.
- `$$`
  - This variable represents the current Process ID of the shell, unrelated to the positional parameters.

**Hint:** The "At" symbol.

### 22. What is the result of echo ${#VAR}?

- It displays the current memory address of VAR
  - Bash does not provide a direct way to view memory addresses of variables using this syntax.
- **It returns the character length of the variable** ✅
  - The hash prefix inside curly braces is the specific operator for measuring string length in Bash.
- It generates a cryptographic hash of the value
  - Cryptographic hashing requires external tools like sha256sum; the shell itself does not hash via this syntax.
- It lists the number of times VAR was updated
  - Bash does not track the update history or version count of variables automatically.

**Hint:** The hash symbol before the name.

### 23. How do you check if a file is a directory?

- `[ -f "$FILE" ]`
  - The -f flag checks if the path is a regular file, excluding directories and special device files.
- **`[ -d "$FILE" ]`** ✅
  - The -d flag evaluates to true only if the specified path exists and is classified as a directory.
- `[ -x "$FILE" ]`
  - The -x flag tests for execution permissions but does not distinguish between files and directories.
- `[ -s "$FILE" ]`
  - The -s flag checks if a file exists and contains data (size greater than zero) regardless of its type.

**Hint:** Think "Directory".

### 24. What is the purpose of the "alias" command?

- To change the owner of a file or directory
  - File ownership is modified using the chown command; alias is used for command shortcuts.
- **To create a custom shortcut for a command** ✅
  - Aliases allow users to map a short string to a longer, complex command for efficiency.
- To hide a specific file from the directory list
  - Hiding files is achieved by naming them with a leading dot, not by using the alias command.
- To synchronize a local file with a remote host
  - Synchronization is handled by rsync or similar tools; alias is a local shell string mapping.

**Hint:** A nickname for a command.

### 25. Which command is used to replace text in a stream using regex?

- grep
  - Grep is used to locate and print lines that match a pattern, but it cannot modify the text.
- **sed** ✅
  - The Stream Editor (sed) is the standard tool for performing search-and-replace tasks on text streams.
- cat
  - Cat displays or joins file contents together; it does not have any search-and-replace functionality.
- echo
  - Echo simply prints the provided arguments to the terminal and cannot perform regex replacements.

**Hint:** Stream Editor.

### 26. How do you evaluate if $A is equal to $B for integers?

- `[ $A = $B ]`
  - The single equals sign is the standard operator for string comparison in the test command.
- **`[ $A -eq $B ]`** ✅
  - The -eq flag is the specific numeric operator used to test for integer equality in a test block.
- `[ $A is $B ]`
  - Bash does not recognize "is" as a comparison operator; this is a syntax error in shell scripts.
- `[ $A == $B ]`
  - While Bash-specific tests [[ ]] allow == for numbers, the POSIX test [ ] uses it for strings.

**Hint:** Integer Equality.

### 27. What happens if you run a command with a leading space (e.g., " command")?

- The command is executed with sudo privileges
  - Elevated privileges always require an explicit command like sudo; a space does not change authority.
- **The command is excluded from the shell history** ✅
  - Many shells are configured to skip logging commands to the history file if they begin with a space.
- The command runs in a separate background process
  - Running in the background requires a trailing ampersand; leading whitespace is ignored for execution mode.
- The command is parsed as a shell comment
  - Comments must begin with the # character; commands with spaces are still executed normally.

**Hint:** History management.

### 28. What is the result of "$(( 10 / 3 ))" in Bash?

- A decimal value of approximately 3.333
  - Bash arithmetic expansion does not support floating-point numbers and cannot return decimals.
- **A truncated integer value of 3** ✅
  - Bash performs integer division, which discards the remainder and returns only the whole number portion.
- A remainder value of 1 from the division
  - The remainder is only returned if the modulo operator (%) is used instead of the division operator.
- A syntax error due to the lack of decimals
  - This is a valid operation in Bash; the shell simply truncates the result to the nearest integer.

**Hint:** Bash math is limited.

### 29. Which command is used to make a script wait for a specific number of seconds?

- pause
  - Pause is used in Windows batch files; Bash scripts utilize the sleep command for timing.
- **sleep** ✅
  - The sleep command halts script execution for a specified duration in seconds or minutes.
- wait
  - Wait is used to monitor background jobs until they finish, not to pause for a fixed time interval.
- delay
  - Delay is not a built-in command in Bash; timing control is exclusively handled by the sleep utility.

**Hint:** Think of "napping".

### 30. What is the purpose of "source script.sh"?

- To download the script from a remote server
  - Downloading requires tools like wget or curl; source is used for local script execution.
- **To run the script within the current shell** ✅
  - Sourcing allows a script to set variables and functions that persist in the user’s active shell session.
- To check the script for potential logic errors
  - Syntax checking is done via bash -n; source actually executes the code and applies changes.
- To convert the script into a binary executable
  - Sourcing executes text directly; it does not compile or transform the file into a binary format.

**Hint:** Running in the current shell.
