Linux+ Linux+ Basic Bash Scripting 3 — Questions and Answers
Question 1: What does the `chmod +x script.sh` command do?
- Compiles the script
- Adds execute permission to the script (Correct answer)
- Removes execute permission from the script
- Changes the script's owner
Correct answer: Adds execute permission to the script
chmod +x adds the execute bit for the owner, group, and others, allowing the file to be run as a program.
Question 2: In a while loop, what does `while read line` typically read from?
- A hardcoded file called 'line'
- Standard input or a piped/redirected source (Correct answer)
- The script's argument list
- The system log
Correct answer: Standard input or a piped/redirected source
while read line reads one line at a time from stdin, which is often piped or redirected from a file.
Question 3: Which arithmetic expression syntax is native to Bash and avoids spawning a subshell?
- `expr 3 + 2`
- $(( 3 + 2 )) (Correct answer)
- $(calc 3+2)
- let '3+2'
Correct answer: $(( 3 + 2 ))
$(( )) is Bash's built-in arithmetic expansion, evaluating expressions without forking an external process.
Question 4: What happens when you use `set -e` at the top of a Bash script?
- The script echoes every command before executing it
- The script exits immediately when any command returns a non-zero status (Correct answer)
- Environment variables are exported automatically
- All errors are redirected to a log file
Correct answer: The script exits immediately when any command returns a non-zero status
set -e (errexit) causes the script to terminate as soon as any command exits with a non-zero status.
Question 5: Which syntax correctly passes all positional parameters as individual quoted arguments to another command?
- $*
- "$*"
- "$@" (Correct answer)
- $#
Correct answer: "$@"
"$@" expands each positional parameter as a separate quoted word, preserving spaces within arguments.
Question 6: In Bash, what does the `case` statement most closely resemble from other languages?
- A for loop
- A switch/case construct (Correct answer)
- A try/catch block
- A function definition
Correct answer: A switch/case construct
Bash's case statement matches a value against patterns, similar to switch/case in C, Java, or Python's match.
Question 7: What is the effect of placing `2>&1` at the end of a command?
- Redirects stdout to a file named 2
- Sends stderr to the same destination as stdout (Correct answer)
- Suppresses all output
- Runs the command in the background
Correct answer: Sends stderr to the same destination as stdout
2>&1 redirects file descriptor 2 (stderr) to file descriptor 1 (stdout), merging error output with standard output.
What does the `chmod +x script.sh` command do?