Linux Shell Scripting 2 — Questions and Answers
Question 1: Which construct in bash properly iterates over all files in the current directory?
- for f in $(ls); do echo $f; done
- for f in *; do echo "$f"; done (Correct answer)
- foreach f in *; do echo $f; done
- loop f in *; do echo $f; done
Correct answer: for f in *; do echo "$f"; done
Using glob `*` directly is safer than parsing `ls` output, which breaks on filenames with spaces.
Question 2: What does the special variable `$?` represent in a shell script?
- The PID of the current shell
- The exit status of the last command (Correct answer)
- The number of arguments passed
- The name of the script
Correct answer: The exit status of the last command
`$?` holds the exit code of the most recently executed foreground command.
Question 3: How do you redirect both stdout and stderr to the same file in bash?
- cmd > file 2> file
- cmd > file 2>&1 (Correct answer)
- cmd &> /dev/null > file
- cmd 1>&2 > file
Correct answer: cmd > file 2>&1
`2>&1` redirects stderr (fd 2) to wherever stdout (fd 1) currently points, combining both streams.
Question 4: Which command makes a shell script executable?
- chown +x script.sh
- chmod +x script.sh (Correct answer)
- exec script.sh
- bash -x script.sh
Correct answer: chmod +x script.sh
`chmod +x` adds the execute permission bit to the file.
Question 5: What is the purpose of `set -e` at the top of a bash script?
- Enable extended globbing
- Exit the script immediately on any command error (Correct answer)
- Echo each command before executing it
- Enable environment variable export
Correct answer: Exit the script immediately on any command error
`set -e` causes the script to exit immediately if any command returns a non-zero exit status.
Question 6: Which syntax correctly defines a function named `greet` in bash?
- function greet() => { echo hi; }
- greet() { echo hi; } (Correct answer)
- def greet(): echo hi
- func greet { echo hi }
Correct answer: greet() { echo hi; }
In bash, `name() { commands; }` is the standard portable function definition syntax.
Question 7: What does `$(command)` do in a shell script?
- Runs the command in a subshell and discards output
- Captures the command's stdout as a string (Correct answer)
- Executes the command in the background
- Pipes command output to /dev/null
Correct answer: Captures the command's stdout as a string
Command substitution `$(...)` replaces itself with the standard output of the enclosed command.
Which construct in bash properly iterates over all files in the current directory?