LX0-104 · Question #90
After issuing: function myfunction { echo $1 $2 ; } in Bash, which output does: myfunction A B C Produce?
The correct answer is A. A B. When a Bash function myfunction defined to echo $1 $2 is called with arguments A B C, it will print A B. This is because $1 refers to the first argument (A) and $2 refers to the second argument (B), while C is ignored as it is not referenced.
Question
Options
- AA B
- BA B C
- CA C
- DB C
- EC B A
How the community answered
(24 responses)- A96% (23)
- B4% (1)
Why each option
When a Bash function `myfunction` defined to `echo $1 $2` is called with arguments `A B C`, it will print `A B`. This is because `$1` refers to the first argument (`A`) and `$2` refers to the second argument (`B`), while `C` is ignored as it is not referenced.
In Bash scripting, `$1` refers to the first argument passed to a function or script, and `$2` refers to the second argument. The function `myfunction` is defined to `echo` only `$1` and `$2`, so when `myfunction A B C` is executed, it substitutes `A` for `$1` and `B` for `$2`, producing the output "A B". The argument `C` is not captured by any positional parameter in the `echo` command within the function definition.
This would be the output if the function was defined as `echo $@` or `echo $*`, which echoes all arguments.
This output implies the function somehow skipped the second argument and directly accessed the third, which is not how positional parameters work.
This output implies the function accessed the second and third arguments, ignoring the first, which is incorrect for `$1` and `$2`.
This output implies a reversal and access to all arguments, which is inconsistent with `echo $1 $2`.
Concept tested: Bash scripting - positional parameters
Source: https://www.gnu.org/software/bash/manual/bash.html#Positional-Parameters
Topics
Community Discussion
No community discussion yet for this question.