Explanation: The reason why the script.sh does not display the content of the variable MYVAR is that the variable is not exported to the environment of the script. When a script is executed, it runs in a separate process that inherits the environment variables from the parent process, but not the shell variables. A shell variable is a variable that is defined and visible only in the current shell session, while an environment variable is a variable that is exported to the environment and visible to all processes that run in that environment1.
To make a shell variable an environment variable, we need to use the export command. The export command takes a shell variable name and adds it to the environment of the current shell and any subshells or processes that are created from it2. For example, to export the variable MYVAR with the value value, we can use:
export MYVAR=value
This will make the variable MYVAR available to the script.sh when it is executed, and the script will print the value of MYVAR as expected. Alternatively, we can also use the export command with the -n option to remove a variable from the environment, or with the -p option to list all the environment variables2.
The other options are not valid ways to set MYVAR as an environment variable. The !MYVAR=value option is not a valid syntax for setting a variable in bash. The env MYVAR=value option will run the env command with the MYVAR=value argument, which will print the environment variables with the addition of MYVAR=value, but it will not affect the current shell or the script.sh3. The MYVAR=value option will set MYVAR as a shell variable, but not as an environment variable, so it will not be visible to the script.sh1. The $MYVAR=value option will try to set the variable whose name is the value of MYVAR to the value value, which is not what we want4. References:
- Linux Essentials Exam Objectives, Version 1.6, Topic 103.1, Weight 2
- Linux Essentials Certification Guide, Chapter 3, Page 51-52
- env(1) - Linux manual page
- Bash Variables - LinuxConfig.org