102-500 practice question 14 of 30

After issuing: function myfunction { echo $1 $2 ; } in Bash, which output does: myfunction A B C Produce?

Full set: 233 questions
Answer options
A: A B Correct answer
B: A B C
C: A C
D: B C
E: C B A
Correct Answer:
A. A B
Explanation

Bash functions process arguments as positional parameters. The function myfunction is defined to print only the first ($1) and second ($2) parameters it receives. When called as myfunction A B C, the shell assigns A to $1, B to $2, and C to $3. Since the function's echo command only references $1 and $2, it outputs A B, and the third argument C is ignored.

Why Incorrect

B. This is incorrect because the function's definition does not include $3 or a mechanism like $@ to process all arguments.
C. This is incorrect because $2 is assigned the value B, not C. The arguments are processed in the order they are given.
D. This is incorrect because the function is defined to print $1 and $2, not $2 and $3.
E. This is incorrect as it reverses the order of arguments and includes an argument ($3) that the function's code ignores.

References

1. GNU Bash Manual, Section 3.5.3 "Shell Functions". It states, "Positional parameters to the function are set when the function is executed... The special parameter ‘#’ is updated to reflect the change." This confirms functions use positional parameters like scripts.

2. "The Missing Semester of Your CS Education," MIT, 2020, Lecture 2: Shell Tools and Scripting. The lecture notes explain that $1, $2, etc., refer to the script's (or function's) arguments.

Scroll to Top