010-150 · Question #61
Which of the following statements may be used to access the second command line argument to a script?
The correct answer is C. "$2". In shell scripting, positional parameters are accessed with $1, $2, etc., and quoting with double quotes preserves the value while allowing variable expansion.
Question
Which of the following statements may be used to access the second command line argument to a script?
Options
- A"$ARG2"
- B$1
- C"$2"
- D"$1"
- E'$2'
How the community answered
(24 responses)- B4% (1)
- C79% (19)
- D13% (3)
- E4% (1)
Why each option
In shell scripting, positional parameters are accessed with `$1`, `$2`, etc., and quoting with double quotes preserves the value while allowing variable expansion.
`$ARG2` is not a standard shell positional parameter; it would only work if explicitly defined elsewhere in the script.
`$1` accesses the first command line argument, not the second.
The variable `$2` refers to the second positional argument passed to a script. Enclosing it in double quotes (`"$2"`) is best practice because it prevents word splitting and glob expansion on the value while still expanding the variable correctly.
`"$1"` also accesses the first argument, not the second.
Single quotes (`'$2'`) prevent variable expansion entirely, so the literal string `$2` is output rather than the argument value.
Concept tested: Shell positional parameters and argument access
Source: https://www.gnu.org/software/bash/manual/bash.html#Positional-Parameters
Topics
Community Discussion
No community discussion yet for this question.