nerdexam
LPI

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.

Development

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)
  • A
    6% (2)
  • B
    74% (26)
  • C
    14% (5)
  • D
    3% (1)
  • E
    3% (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.

Atest1 test2

test1 test2 would result only if the script echoed $1 $2 in that order, but the script reverses them with echo $2 $1.

Btest2 test1Correct

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'.

Cscript.sh test2

script.sh is stored in $0, the script name, not $2; $2 holds the second argument 'test2'.

Dscript.sh test1

script.sh is stored in $0, the script name, not $1; $1 holds the first argument 'test1'.

Etest1 script.sh

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

#bash scripting#positional parameters#shell variables#script execution

Community Discussion

No community discussion yet for this question.

Full 010-100 Practice