010-100 · Question #3
The script, script.sh, consists of the following lines: #!/bin/bash echo $2 $1 Which output will appear if the command, ./script.sh test1 test2, is entered?
The correct answer is B. test2 test1. In bash, positional parameters $1 and $2 map to the first and second arguments passed to the script, and echo outputs them in the order specified in the script.
Question
The script, script.sh, consists of the following lines:
#!/bin/bash echo $2 $1 Which output will appear if the command, ./script.sh test1 test2, is entered?
Options
- Atest1 test2
- Btest2 test1
- Cscript.sh test2
- Dscript.sh test1
- Etest1 script.sh
How the community answered
(35 responses)- A6% (2)
- B74% (26)
- C14% (5)
- D3% (1)
- E3% (1)
Why each option
In bash, positional parameters $1 and $2 map to the first and second arguments passed to the script, and echo outputs them in the order specified in the script.
test1 test2 would result only if the script echoed $1 $2 in that order, but the script reverses them with echo $2 $1.
When ./script.sh test1 test2 is run, $1 is assigned 'test1' and $2 is assigned 'test2'; because the script echoes $2 before $1, the output is 'test2 test1'.
script.sh is stored in $0, the script name, not $2; $2 holds the second argument 'test2'.
script.sh is stored in $0, the script name, not $1; $1 holds the first argument 'test1'.
The script name ($0) is not referenced in the echo statement at all, so it cannot appear in the output.
Concept tested: Bash positional parameters and script argument ordering
Source: https://www.gnu.org/software/bash/manual/bash.html#Positional-Parameters
Topics
Community Discussion
No community discussion yet for this question.