Linux+ Linux+ Basic Bash Scripting 2 — Questions and Answers
Question 1: Which operator is used to append output to an existing file in Bash?
- >
- >> (Correct answer)
- |
- &>
Correct answer: >>
The >> operator appends output to a file without overwriting its existing contents.
Question 2: What does the special variable $? represent in Bash?
- The current process ID
- The script's filename
- The exit status of the last command (Correct answer)
- The number of arguments passed
Correct answer: The exit status of the last command
$? holds the exit status of the most recently executed command, where 0 typically means success.
Question 3: Given the script: `for i in {1..5}; do echo $i; done`, what is the output?
- Prints 1 through 5 each on a new line (Correct answer)
- Prints {1..5} literally
- Prints 0 through 4
- Causes a syntax error
Correct answer: Prints 1 through 5 each on a new line
Brace expansion {1..5} generates the sequence 1 2 3 4 5, so the loop prints each number on its own line.
Question 4: Which command inside a Bash function returns a value to the caller?
- exit
- return (Correct answer)
- break
- yield
Correct answer: return
The return statement exits a function and sets its exit status code, which the caller can read via $?.
Question 5: What is the purpose of the `read` command in a Bash script?
- Reads the contents of a file into memory
- Reads a line of input from stdin into a variable (Correct answer)
- Reads the next command from the script
- Displays file contents to stdout
Correct answer: Reads a line of input from stdin into a variable
The read command pauses execution and stores a line of user input (or piped input) into one or more variables.
Question 6: In Bash, what does `[ -d /etc ]` test?
- Whether /etc is a regular file
- Whether /etc exists and is a directory (Correct answer)
- Whether /etc is readable
- Whether /etc is non-empty
Correct answer: Whether /etc exists and is a directory
The -d flag in a test expression returns true if the given path exists and is a directory.
Question 7: Which shebang line correctly specifies Bash as the interpreter for a script?
- # /bin/bash
- #!/usr/bin/env bash (Correct answer)
- #bash
- //bin/bash
Correct answer: #!/usr/bin/env bash
#!/usr/bin/env bash is the portable shebang that finds bash via the PATH, recommended over hardcoded paths.
Which operator is used to append output to an existing file in Bash?