010-160 Basic Scripting Concepts 3 — Questions and Answers
Question 1: In a bash `for` loop written as `for i in 1 2 3 4 5; do echo $i; done`, how many times does the loop body execute?
- 4
- 6
- 5 (Correct answer)
- 3
Correct answer: 5
The loop iterates once for each word in the list, which contains five elements.
Question 2: What does the `shift` command do inside a shell script?
- Moves the cursor to the next line
- Discards the last positional parameter
- Shifts positional parameters left, dropping $1 (Correct answer)
- Converts $@ to an array
Correct answer: Shifts positional parameters left, dropping $1
`shift` removes `$1` and renumbers remaining positional parameters so `$2` becomes `$1`, and so on.
Question 3: Which quoting style prevents ALL special-character interpretation in bash?
- Double quotes ""
- Single quotes '' (Correct answer)
- Backticks ``
- Dollar-sign braces ${}
Correct answer: Single quotes ''
Single quotes preserve the literal value of every character inside them with no exceptions.
Question 4: What is the purpose of the `break` statement inside a loop?
- Skips the current iteration and continues with the next
- Exits the script immediately
- Exits the innermost loop (Correct answer)
- Resets the loop counter to zero
Correct answer: Exits the innermost loop
`break` terminates execution of the innermost enclosing loop and resumes after it.
Question 5: Which variable holds all positional parameters passed to a script as a single quoted string?
- $@
- $* (Correct answer)
- $#
- $0
Correct answer: $*
`$*` expands all positional parameters as a single word joined by the first character of IFS.
Question 6: What will `echo ${#name}` print if `name="Linux"`?
- Linux
- 5 (Correct answer)
- name
- 0
Correct answer: 5
The `${#var}` expansion returns the length in characters of the variable's value.
Question 7: In a `case` statement, which pattern acts as a catch-all (default) match?
- default)
- else)
- *) (Correct answer)
- any)
Correct answer: *)
The `*)` pattern matches any string not matched by earlier patterns, serving as the default case.
In a bash `for` loop written as `for i in 1 2 3 4 5; do echo $i; done`, how many times does the loop body execute?