010-160 · Question #59
Which of the following statements may be used to access the second command line argument to a script?
The correct answer is C. "$2". The shell assigns command-line arguments to positional parameters $1, $2, $3, etc., so $2 holds the second argument.
Question
Options
- A"$ARG2"
- B"$1"
- C"$2"
- D"$S2"
- E'$2'
How the community answered
(28 responses)- C89% (25)
- D4% (1)
- E7% (2)
Why each option
The shell assigns command-line arguments to positional parameters $1, $2, $3, etc., so $2 holds the second argument.
$ARG2 is not a special shell variable; it would only hold a value if the script explicitly assigned one to it.
$1 holds the first positional argument, not the second.
$2 is the standard POSIX positional parameter for the second command-line argument. The shell automatically populates $1 through $N with successive arguments, making $2 the correct and idiomatic way to access the second one inside a script.
$S2 is not a recognized positional parameter or special shell variable; it would evaluate to an empty string unless explicitly set.
Single quotes suppress all parameter expansion in bash, so '$2' produces the literal four-character string $2 rather than the value of the second argument.
Concept tested: Shell script positional parameter access
Source: https://www.gnu.org/software/bash/manual/bash.html#Positional-Parameters
Topics
Community Discussion
No community discussion yet for this question.