LFCS · 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 the Bash function myfunction is called with A B C, it only echoes the first two positional parameters, $1 and $2, resulting in "A B".
Question
Options
- AA B
- BA B C
- CA C
- DB C
- EC B A
How the community answered
(57 responses)- A84% (48)
- B2% (1)
- C4% (2)
- D2% (1)
- E9% (5)
Why each option
When the Bash function `myfunction` is called with `A B C`, it only echoes the first two positional parameters, `$1` and `$2`, resulting in "A B".
In Bash, `$1` refers to the first argument passed to a function or script, and `$2` refers to the second. The function `myfunction` is defined to `echo` only `$1` and `$2`. When called with `A B C`, `A` becomes `$1`, `B` becomes `$2`, and `C` is `$3` but is not used by the function's `echo` command.
`A B C` would be produced if the function echoed `$1 $2 $3` or all arguments like `$@`.
`A C` would require the function to explicitly skip `$2`.
`B C` would mean the function ignored `$1` and started from `$2` and `$3`.
`C B A` would require specific reversal logic not present in the function.
Concept tested: Bash function positional parameters
Source: https://www.gnu.org/software/bash/manual/bash.html#Shell-Functions
Topics
Community Discussion
No community discussion yet for this question.