010-160 Basic Scripting Concepts 4 — Questions and Answers
Question 1: What does the `-z` test operator check in `[ -z "$var" ]`?
- Whether $var is a number
- Whether $var contains only zeros
- Whether $var is an empty string (Correct answer)
- Whether $var is unset
Correct answer: Whether $var is an empty string
`-z` returns true when the string has a length of zero.
Question 2: Which command substitution syntax is POSIX-compatible and preferred in modern scripts?
- `command`
- $(command) (Correct answer)
- ${command}
- ((command))
Correct answer: $(command)
`$(command)` is the modern, nestable form of command substitution recommended by POSIX.
Question 3: What value does `$#` represent in a shell script?
- The PID of the script
- The name of the script
- The number of positional parameters passed (Correct answer)
- The last exit status
Correct answer: The number of positional parameters passed
`$#` expands to the count of positional parameters supplied when the script was invoked.
Question 4: How do you make a script file executable so it can be run as `./myscript.sh`?
- chmod +r myscript.sh
- chmod +x myscript.sh (Correct answer)
- chown +x myscript.sh
- bash +x myscript.sh
Correct answer: chmod +x myscript.sh
`chmod +x` adds the execute permission bit, allowing the file to be run directly.
Question 5: In bash, what is the correct way to compare two integer variables `a` and `b` for equality inside `[ ]`?
- [ $a == $b ]
- [ $a -eq $b ] (Correct answer)
- [ $a = $b ]
- [ $a EQ $b ]
Correct answer: [ $a -eq $b ]
`-eq` is the arithmetic equality operator used inside `[ ]` for numeric comparisons.
Question 6: Which construct runs a block of commands repeatedly as long as a condition is TRUE?
- until loop
- for loop
- while loop (Correct answer)
- case statement
Correct answer: while loop
A `while` loop evaluates its condition before each iteration and continues as long as it is true.
Question 7: What happens if you use `local` to declare a variable inside a bash function?
- The variable is exported to child processes
- The variable is read-only
- The variable is only visible within the function (Correct answer)
- The variable is stored permanently in the environment
Correct answer: The variable is only visible within the function
`local` restricts the variable's scope to the function and its children, preventing pollution of the global namespace.
What does the `-z` test operator check in `[ -z "$var" ]`?