nerdexam
LPI

010-160 · Question #92

The file script.sh in the current directory contains the following content: #!/bin/bash echo $MYVAR The following commands are used to execute this script: MYVAR=value ./script.sh The result is an…

The correct answer is E. export MYVAR=value. Shell variables are not automatically inherited by child processes. Using export marks a variable for inclusion in the environment of subsequently executed commands, including subshells like ./script.sh.

The Power of the Command Line

Question

The file script.sh in the current directory contains the following content: #!/bin/bash echo $MYVAR The following commands are used to execute this script: MYVAR=value ./script.sh The result is an empty line instead of the content of the variable MYVAR. How should MYVAR be set in order to make script.sh display the content of MYVAR?

Options

  • A!MYVAR=value
  • Benv MYVAR=value
  • CMYVAR=value
  • D$MYVAR=value
  • Eexport MYVAR=value

How the community answered

(32 responses)
  • A
    3% (1)
  • B
    6% (2)
  • C
    3% (1)
  • D
    16% (5)
  • E
    72% (23)

Why each option

Shell variables are not automatically inherited by child processes. Using `export` marks a variable for inclusion in the environment of subsequently executed commands, including subshells like `./script.sh`.

A!MYVAR=value

`!MYVAR=value` is not valid shell syntax for variable assignment.

Benv MYVAR=value

`env MYVAR=value` without a following command only prints the environment or is incomplete; it does not persistently export the variable for subsequent standalone invocations.

CMYVAR=value

`MYVAR=value` sets the variable only in the current shell session and does not export it, so child processes like `./script.sh` cannot access it.

D$MYVAR=value

`$MYVAR=value` is invalid syntax; variable names on the left side of an assignment must not be prefixed with `$`.

Eexport MYVAR=valueCorrect

When a script is executed as a subprocess with `./script.sh`, it runs in its own shell environment. Variables defined in the parent shell without `export` are local to that shell and invisible to child processes. Using `export MYVAR=value` promotes the variable to an environment variable, which is inherited by any child process, causing the script to see and print the value.

Concept tested: Exporting shell variables to child process environments

Source: https://www.gnu.org/software/bash/manual/bash.html#index-export

Topics

#export command#environment variables#variable scope#shell scripting

Community Discussion

No community discussion yet for this question.

Full 010-160 Practice