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.
Question
Options
- A!MYVAR=value
- Benv MYVAR=value
- CMYVAR=value
- D$MYVAR=value
- Eexport MYVAR=value
How the community answered
(32 responses)- A3% (1)
- B6% (2)
- C3% (1)
- D16% (5)
- E72% (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`.
`!MYVAR=value` is not valid shell syntax for variable assignment.
`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.
`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.
`$MYVAR=value` is invalid syntax; variable names on the left side of an assignment must not be prefixed with `$`.
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
Community Discussion
No community discussion yet for this question.