Chapter 4: Linux Advanced Commands
4.10 Environment variables
Environment variables are named text values supplied to a process. Use examples like a workshop label to practice how export affects child processes. Give real credentials through the approved deployment mechanism.
Environment variables म्हणजे process ला मिळणारी नाव असलेली text values. Workshop label वापरून export नंतर child process ला काय मिळते ते तपासा. वास्तविक credentials साठी deployment ची मंजूर पद्धत वापरा.
Environment variables किसी process को मिलने वाली नाम वाली text values हैं। Workshop label से देखें कि export के बाद child process को क्या मिलता है। वास्तविक credentials के लिए deployment का स्वीकृत तरीका इस्तेमाल करें।
(
unset WORKSHOP_MODE
WORKSHOP_MODE=training
printf 'shell: %s\n' "$WORKSHOP_MODE"
export WORKSHOP_MODE
printenv WORKSHOP_MODE
unset WORKSHOP_MODE
printf 'after unset: %s\n' "${WORKSHOP_MODE-absent}"
)Keep secrets out of code
Keep passwords out of source code, Git history, and diagnostic output. Use the secret store or workload identity approved for the deployment. Ordinary environment settings and .env files are readable configuration surfaces, with visibility determined by the launcher and access controls.
Ravindra Bagale's Tip
An export affects the current shell’s future children. Bash reads different startup files depending on how it starts. Test with a new shell and the intended launcher. Write assignments like WORKSHOP_LABEL="Opening shift" without spaces around the equal sign.
Ravindra Bagale's Tip – मराठी
Export केलेली value या shell मधून नंतर सुरू होणाऱ्या child processes ला मिळते. Bash कशी सुरू झाली यावर startup file अवलंबून असते. WORKSHOP_LABEL="Opening shift" मध्ये equal sign भोवती spaces देऊ नका.
Ravindra Bagale's Tip – हिंदी
Export की गई value उस shell से बाद में शुरू होने वाले child processes को मिलती है। Bash कैसे शुरू हुई, इससे startup file तय होती है। WORKSHOP_LABEL="Opening shift" में equal sign के आसपास spaces न दें।
Lab
खालील workshop lab मध्ये WORKSHOP_MODE आधी shell मध्ये सेट करा, मग export करून child process मध्ये पहा. Startup चाचणीसाठी scratch rc file वापरा.
Give a program the settings for this run
The Mauli workshop uses the same report program on a student's laptop and on a training server. The program should label one report as a practice run and another as a morning handover. It should also read input from a different directory in each environment. Rewriting the program for every setting makes it harder to review which logic is shared. Supplying ordinary configuration when the program starts lets it do the same work with explicit inputs. In this lesson the settings are harmless labels and paths, and no credentials are needed.
A process's environment is a collection of named string values available to that running program. A program can read a value like WORKSHOP_MODE when it chooses how to behave. It can ignore the value if it has no such configuration setting. The environment is one possible input alongside arguments, config files, files the program discovers, and defaults. Success depends on knowing which input the application actually reads and how it handles several competing sources.
A shell variable is a named value kept by that shell. In Bash it can be used to construct a command or choose what a script does. The shell only passes an ordinary shell variable into a newly executed external program's environment when it has the export attribute or is supplied specially for that command. Many familiar names are already exported by the environment that started your shell. An assignment can change one of those existing names without removing its export attribute. This is why the lab starts in subshells and clears its own variable names before observing them.
Use Bash on your Linux or local Unix-like training machine. The exercise uses /bin/sh to model a new shell process and a private scratch directory where it needs files. The example deliberately prints only invented configuration values. An actual machine's environment can contain tokens and other confidential values, so avoid dumping all of it into a shared terminal recording or log. The sections are independent except where one explicitly reuses the prepared fixture. No persistent shell startup file or service configuration needs to change.
Watch a value cross the process boundary
In the following block, the outer parentheses run a Bash subshell that isolates the exercise from your usual terminal. Start by assigning a variable without spaces around the equal sign. The right side is a string. Double quoting a value such as morning review keeps it as one value. The first printf reads it from the current shell. The external /bin/sh process starts with the exported environment, so before you export this new name it should have no value for it.
(
unset WORKSHOP_MODE
WORKSHOP_MODE="morning review"
printf 'current shell: [%s]\n' "$WORKSHOP_MODE"
/bin/sh -c 'printf "child before export: [%s]\n" "${WORKSHOP_MODE-unset}"'
export WORKSHOP_MODE
/bin/sh -c 'printf "child after export: [%s]\n" "${WORKSHOP_MODE-unset}"'
)
current shell: [morning review]
child before export: [unset]
child after export: [morning review]
The brackets are just markers that make surrounding spaces visible. The single quotes around the child command keep the parent from replacing its variable reference before passing the command to the child. Inside that command, the new shell expands the value in its own environment. The form ${WORKSHOP_MODE-unset} substitutes the word unset only when the variable is absent. This tells you more than an empty display would. If the current shell had set and exported an empty value, the new shell would see a defined value with no characters between the brackets.
Export makes this value available to future commands launched with that environment. It does not reach backward into a process that already started, and it does not set the same value in every terminal on the machine. A new terminal created through a separate launcher inherits the environment of that launcher and reads whichever startup files apply to its shell mode. A new shell you launch directly as a child of your current shell can inherit a variable from the current one. The relationship between the processes explains why the two seemingly similar terminal tests can give different observations.
The inheritance is also one-way for ordinary changes. The next example exports a value, starts a child that changes and exports its own copy, and then tests a second child. The first child can affect its own descendants, while the terminal's original shell keeps the value it already had. A command that claims to set the parent terminal's environment must run code in that terminal, have the caller apply returned instructions, or use another explicit mechanism. Running a separate script ordinarily cannot assign a variable in the caller.
(
export WORKSHOP_MODE=training
/bin/sh -c 'export WORKSHOP_MODE=handover; printf "first child: %s\n" "$WORKSHOP_MODE"'
printf 'parent after child: %s\n' "$WORKSHOP_MODE"
/bin/sh -c 'printf "second child: %s\n" "$WORKSHOP_MODE"'
)
first child: handover
parent after child: training
second child: training
The shells share an initial value across the process boundary, which then belongs to each process. If the first child had invoked another program after changing the value, its descendant would inherit handover. The second child was started by the parent whose value stayed training. This explains a configuration issue after exporting a new setting in one terminal and asking why a service that started hours earlier has kept the old behavior. Update the place the service manager uses to supply configuration and follow the supported way to apply it to a new invocation.
Override one command while keeping the normal setting
A command prefix can supply a setting for one external command. This is useful when testing the workshop's safe preview mode without changing commands you launch afterward. In the first line below, export the ordinary value in the isolated shell. Put a different assignment before the explicit /bin/sh program. That external program receives the temporary environment value. The command after it runs in the unchanged caller and reads the ordinary one.
(
export WORKSHOP_MODE=training
WORKSHOP_MODE=preview /bin/sh -c 'printf "one run: %s\n" "$WORKSHOP_MODE"'
printf 'after one run: %s\n' "$WORKSHOP_MODE"
)
one run: preview
after one run: training
Compare the prefix with a command where the outer shell expands the value as an argument. The string after a dollar sign in a normal argument can be expanded by the caller before the temporary environment is used by the new program. If the ordinary value is training, WORKSHOP_MODE=preview /bin/echo "$WORKSHOP_MODE" can print training because the caller passed that text as an argument. The echo process does not look up a variable at all. In the sh example, the shell program is given the literal variable reference and then expands it under the temporary environment.
You can also use the env utility to start an external command with selected settings. For example, env WORKSHOP_MODE=preview /bin/sh -c 'printf "%s\n" "$WORKSHOP_MODE"' supplies the same one-run override. The explicit launch mechanism is easy to read when several values are involved. Variables that control an application's mode are ordinary strings until the application interprets them. Setting a label like production does not create a production environment, and a program that does not recognize the key will not automatically become aware of it.
Find out which executable wins a name lookup
PATH is a colon-separated search list for external programs. A shell that needs to find a named executable checks eligible directories in order. If two directories each contain a program called workshop-preview, the order can determine which copy runs. Builtins, shell functions, and aliases have their own precedence in a normal shell, so use a fresh shell and an invented name to demonstrate the directory search alone. The shell can also remember previously found paths, which is another reason to read the actual chosen path before blaming the program.
Use the next block to create a pair of executable scripts with identical names and different identifying messages. They each use a known interpreter and perform only a print. The scratch paths are new. Each command runs in a minimal environment and the synthetic PATH sets the two directories in a different order. The shell starts through its explicit absolute path, so it does not need to search those artificial directories to find itself.
env_lab=$(mktemp -d) || exit 1
printf 'Lab directory: %s\n' "$env_lab"
mkdir "$env_lab/class-a" "$env_lab/class-b" "$env_lab/home"
cat > "$env_lab/class-a/workshop-preview" <<'SCRIPT'
#!/bin/sh
printf 'preview from class A\n'
SCRIPT
cat > "$env_lab/class-b/workshop-preview" <<'SCRIPT'
#!/bin/sh
printf 'preview from class B\n'
SCRIPT
chmod u+x "$env_lab/class-a/workshop-preview" "$env_lab/class-b/workshop-preview"
env -i "PATH=$env_lab/class-a:$env_lab/class-b" /bin/sh -c 'command -v workshop-preview; workshop-preview'
env -i "PATH=$env_lab/class-b:$env_lab/class-a" /bin/sh -c 'command -v workshop-preview; workshop-preview'
Lab directory: /.../tmp.EXAMPLE
/.../tmp.EXAMPLE/class-a/workshop-preview
preview from class A
/.../tmp.EXAMPLE/class-b/workshop-preview
preview from class B
The full directory names vary. The line from command -v identifies which candidate the new shell found. The small executable's message confirms the observed selection independently. In a real diagnostic, try command -v name in the same account and execution environment that showed the unexpected behavior. Bash's type -a name can show other candidates and definitions. A command launched with a path containing a slash refers to that path directly instead of performing the usual PATH lookup for that word. The exact executable used can matter if two tools share a name but support different options.
An empty component of some shell search paths can refer to the current working directory. Prepending an arbitrary directory can also put unintended executables ahead of familiar tools. For a script depending on trusted programs, choose known directories and avoid inheriting an unreviewed search list. At a login prompt you may want to add your own bin directory as a deliberate convenience, but apply the change in a reviewed startup file for the appropriate shell and verify the result. This experiment does not modify your real PATH.
Other names often describe the context of the current process. HOME is typically the user's home directory supplied by the launcher or login configuration. USER and LOGNAME can be useful labels but may be absent or overridden. To ask for the effective account of this process, use an identity command such as id -un rather than treating a writable string as authentication. SHELL often refers to a configured login shell and need not name the particular shell executing a script now. The shell started in our command is determined by the explicit /bin/sh argument regardless of those labels.
A minimal environment is a testing tool, not a different account or a sandbox. An env -i command still has the current process's permissions and open context. It can read files permitted to that user and may still run in the current working directory. The locale and search path can change when the missing values take their defaults. Add only the settings needed for the particular repeatable test and keep its data under the scratch path. The predicted result here depends solely on two executable files and their explicit search order.
Distinguish missing values from intentionally empty values
A configuration program often needs to decide whether a value was provided and whether an empty value is valid. Suppose the workshop's optional label should be default-label when omitted. An explicitly empty label could be a deliberate request to display no label. Bash and compatible shells distinguish these states in parameter expansion. ${NAME-default} uses default when the variable is unset. The colon in ${NAME:-default} adds the case where the defined value is empty. Pick the behavior that fits the actual setting.
(
unset WORKSHOP_LABEL
printf 'unset: [%s] [%s]\n' "${WORKSHOP_LABEL-default-label}" "${WORKSHOP_LABEL:-default-label}"
WORKSHOP_LABEL=
printf 'empty: [%s] [%s]\n' "${WORKSHOP_LABEL-default-label}" "${WORKSHOP_LABEL:-default-label}"
WORKSHOP_LABEL="shift B"
printf 'value: [%s] [%s]\n' "${WORKSHOP_LABEL-default-label}" "${WORKSHOP_LABEL:-default-label}"
)
unset: [default-label] [default-label]
empty: [] [default-label]
value: [shift B] [shift B]
The six displayed values show why an empty output alone is ambiguous. A service expected to receive a nonempty directory should validate it before constructing a pathname. A script could require ${WORKSHOP_DATA_DIR:?missing data directory}, which causes a noninteractive shell to report a message and exit when the variable is missing or empty. State which settings are optional and which must be present. A default label is harmless, while falling back from an unknown output location to a live directory may change important behavior. Validate values with the application as well as checking that an assignment succeeded.
Another way to check whether a setting is present without printing its value is a branch using ${NAME+x}. It expands to the marker x when the variable exists, even if empty. Use a variable name that is meaningful to your script and test in the actual program's own environment. Printing all variables or shell state to diagnose one setting can expose unrelated tokens. For an approved nonsecret setting you may print its specific value with a fixed format. For a secret, diagnose presence, source, and access with tools that avoid revealing the contents.
Observe which startup file a shell reads
Putting an assignment in a file can arrange for future processes to get it, provided the appropriate launcher reads that file. Bash has different startup rules for login and interactive non-login shells. A typical interactive non-login Bash reads ~/.bashrc. A login Bash checks its login startup files in a documented order, and a chosen profile may explicitly read the bashrc file. Neither a remote session nor another shell is guaranteed to have the same rules. Noninteractive Bash has its own mechanism involving BASH_ENV under applicable conditions. Ordinary daemons do not inherit the environment of the interactive shell that happened to be open on your laptop.
This lab gives a new Bash an explicit startup file for a controlled comparison. The new home path is private to this fixture. The first command runs a noninteractive Bash with normal startup files disabled and a fresh environment. The second requests an interactive Bash and uses the scratch file as its explicit rc file. The -c option lets both print a value and then exit immediately. You can read the results without editing your own home-directory startup files.
cat > "$env_lab/workshop.rc" <<'RC'
export WORKSHOP_MODE="from workshop rc"
RC
env -i "HOME=$env_lab/home" PATH=/usr/bin:/bin \
/bin/bash --noprofile --norc -c 'printf "noninteractive: [%s]\n" "${WORKSHOP_MODE-unset}"'
env -i "HOME=$env_lab/home" PATH=/usr/bin:/bin \
/bin/bash --noprofile --rcfile "$env_lab/workshop.rc" -ic \
'printf "interactive with selected rc: [%s]\n" "${WORKSHOP_MODE-unset}"'
noninteractive: [unset]
interactive with selected rc: [from workshop rc]
A shell forced into interactive mode without an interactive terminal can print job-control diagnostics as it starts. Those messages are separate from the intended two observations. The customized environment provides no initial workshop value. The output from the second shell comes from reading the explicit startup file. An already started program will not acquire the file's new value retroactively. To check a long-lived program, identify how it was actually started and whether its configuration source has been applied to the invocation you are examining.
Manual sourcing is also possible with the trusted file you just wrote. Bash's source command, or the corresponding dot command in compatible shells, reads shell instructions into the current shell process. Executing a file through another interpreter process instead keeps its assignments in that child. This distinction matters because sourcing is code execution in the current shell, with access to its variables and functions. Only source files you intend to execute. For a data file written by an application, use its documented configuration parser.
(
unset WORKSHOP_MODE
/bin/bash "$env_lab/workshop.rc"
printf 'after running child: [%s]\n' "${WORKSHOP_MODE-unset}"
. "$env_lab/workshop.rc"
printf 'after reading trusted rc: [%s]\n' "$WORKSHOP_MODE"
)
after running child: [unset]
after reading trusted rc: [from workshop rc]
The dot command is only the period followed by a separate filename argument. Here the file contains one export line that you know and control. The assignment becomes part of the surrounding subshell and then disappears when that subshell exits. Bash's source spelling is useful when talking about the operation, and the dot spelling is available in POSIX shells. For long-term interactive configuration, decide whether the setting belongs to a login profile or another shell startup entry. For scheduled jobs and services, put the setting in the job's own launch configuration instead of expecting an unrelated profile to be loaded.
Give each configuration source a defined priority
An application may read both a file and environment variables. Think through the behavior before setting both. Suppose the workshop report's built-in label is training, a deployment file supplies the value morning, and a one-run override requests preview. A common design lets the explicit environment replace the file setting for the new process, and uses the built-in label only when neither source is present. This priority is a choice made by the application. A tool can use a different order or interpret an empty value in its own way. Look for documented precedence rather than assuming a universal rule.
The following minimal report demonstrates three levels with a file containing just one literal value. Use Python 3 if it is available for this optional example. The file is a plain .txt fixture whose whole text is the label, which keeps the parsing deliberately simple. The tested environment key can override it. The final program outcome prints a harmless mode and which source provided it. It accepts exactly three training labels. Do not generalize this small file reader into a parser for other kinds of configuration.
cat > "$env_lab/show-mode.py" <<'PYTHON'
import os
from pathlib import Path
import sys
mode_file = Path(sys.argv[1])
if "WORKSHOP_MODE" in os.environ:
mode, source = os.environ["WORKSHOP_MODE"], "environment"
elif mode_file.is_file():
mode, source = mode_file.read_text(encoding="utf-8").strip(), "file"
else:
mode, source = "training", "built-in default"
if mode not in {"training", "morning", "preview"}:
print(f"Invalid workshop mode from {source}", file=sys.stderr)
sys.exit(2)
print(f"mode={mode} source={source}")
PYTHON
(
unset WORKSHOP_MODE
python3 "$env_lab/show-mode.py" "$env_lab/mode.txt"
printf '%s\n' morning > "$env_lab/mode.txt"
python3 "$env_lab/show-mode.py" "$env_lab/mode.txt"
WORKSHOP_MODE=preview python3 "$env_lab/show-mode.py" "$env_lab/mode.txt"
if WORKSHOP_MODE= python3 "$env_lab/show-mode.py" "$env_lab/mode.txt"; then
printf 'Unexpected success for an empty override\n'
else
printf 'empty override status=%s\n' "$?"
fi
)
mode=training source=built-in default
mode=morning source=file
mode=preview source=environment
Invalid workshop mode from environment
empty override status=2
The invalid-mode message goes to stderr, so its relative display order can vary across captured streams. Its value is deliberately absent from the diagnostic. The final test tells the application the variable exists with an empty string. The program validates it as an explicit override and reports an error instead of falling back to the file. This illustrates a precedence policy in a way that a single environment dump cannot. When testing an application you do not own, use its supported configuration view or a harmless sample input to verify which setting actually took effect.
When installing software, a .env file is a convention some frameworks use to hold configuration. There is no global operating system action that loads every file with that name. The launcher or application must explicitly read it, and each library defines how assignments, quoting, interpolation, and override behavior work. A shell script, a systemd environment file, a container tool's variable file, and a library's dotenv file can have related-looking syntax without having the same parser. Keep settings in the form expected by their reader and test unusual values such as spaces, empty strings, and characters used for comments.
Identify the launcher that owns the setting
The workshop report can start in several ways. A person can run it from the current terminal. Cron can launch it under the scheduled account and with the environment described by its setup. Systemd can launch it as the command in a service definition. The settings visible in those three runs can differ even if the executable path is identical. Before changing a variable, identify which launcher starts the process and which configuration instructions that launcher reads. An export at one terminal cannot be a general fix for a process owned by another manager.
For a systemd unit, documented settings such as Environment= and EnvironmentFile= can supply nonsecret variables directly for its execution environment. These are systemd directives, with their own parsing rules. The following is a read-only example of settings for a possible workshop unit. It does not run anything, and the names are examples. When a unit uses an environment file, the manager must be able to read it in the manager’s own filesystem view.
[Service]
Environment="WORKSHOP_MODE=morning"
Environment="WORKSHOP_LABEL=Opening shift"
The quotes preserve a single assignment with spaces in the value. They do not turn systemd's directive into shell source. In particular, shell-style dollar expansion is not performed inside this directive as it would be in the arguments of an interactive shell command. This is relevant if a student copies $HOME or $PATH from a shell example. Use the manager's documented syntax and explicit values intended for the service. Check whether your definition is a system unit or a user unit and whether the manager sees the expected configuration files.
After a reviewed change to a service unit or its drop-in configuration, the manager can need a daemon reload to reread unit definitions. The active process also needs the application's supported procedure to receive the new configuration. A process does not generally refresh its original environment when the manager reads a file. Where replacing that process is the supported operation, plan the change with its actual dependencies and verify the new invocation's behavior. A service can use application-level configuration reload for other inputs without changing the environment it inherited at start. Be precise about which kind of configuration you changed.
Cron presents a related choice. A crontab can set variables for jobs in its scope where supported, and an external script can set its own deterministic values. For example, the schedule lesson's report script sets a known PATH before invoking awk and date. An interactive profile would only matter if the job launcher were explicitly configured to read it. As with the service, ask which account and launch environment produced the outcome. This can explain why a saved environment change appears when opening a terminal but not in the morning report.
For a cloud example, the AWS CLI documents its supported environment variables and option priority. An explicitly chosen CLI Region can override a Region from configuration according to those documented rules. A shell experiment that sets a label called REGION has no effect unless the CLI actually reads it. AWS uses defined setting names and an account or role identity supplied through its credential sources. Region describes where a request is directed, and authentication describes who makes the request. Diagnose them separately. No AWS command is required for these environment-variable exercises.
Keep sensitive values out of diagnostics and persistent examples
A database password should never appear in source code or in a file intended for publication. An environment variable can be an input channel for a secret if the deployment is designed that way, but it remains process data and can have other paths to visibility. A launcher can pass it to child processes. An authorized process inspection, a debugging dump, or an error report might expose it. A shell command containing an actual password can also be stored in shell history or shown in a command trace. The protection comes from the architecture and access controls of the secret source and the process, and requires more than changing the spelling of the storage location.
Similarly, a file named .env can still be copied, logged, or committed. A Unix permission mode such as 600 limits certain local reads and writes by file mode if the file's ownership and other controls are correct. It does not encrypt the file or retroactively remove any existing copies. A private filename beginning with a dot is merely less visible in some ordinary listings. Treat a local file as one possible managed input chosen for the context. Use the documented secret-handling mechanism for the actual platform. For example, modern systemd documents credential mechanisms for passing sensitive data to supported services, separate from ordinary environment settings.
For AWS workloads, a role can provide temporary credentials through an approved provider associated with the host or workload. The application can use the documented SDK or CLI provider arrangement instead of a long-lived key written into an interactive startup file. When a password or another application secret must be retrieved, use the organization's approved secret store with access scoped to the workload. Verify that the program can obtain the secret and handle rotation. The details depend on the deployment. This lesson leaves credential providers alone and uses only nonsensitive mode values you can read aloud.
When helping someone debug, ask for evidence about the relevant setting without asking them to publish the whole environment. A service account might have unrelated credentials and proxy settings. A shared output from env, printenv with no names, or shell tracing can reveal those values. For this lab a direct print of WORKSHOP_MODE is safe because it is a known fictional label. For a sensitive value, presence and missing-state checks can provide evidence without showing length or content. If a value has already been exposed, handle it as an incident under the approved credential revocation and replacement procedure; removing the local line alone does not invalidate it.
Practice a presence-only check on ordinary dummy settings so the habit is familiar. The child below prints whether the specific label is present and whether it contains a value. The program uses tests rather than interpolating the value into the output. This kind of check is useful for identifying which boundary failed. It cannot tell whether the value refers to the intended file or whether the application accepted it. Use application behavior through an authorized test for that further question.
(
unset WORKSHOP_LABEL
for sample in absent empty present; do
case "$sample" in
absent) unset WORKSHOP_LABEL ;;
empty) export WORKSHOP_LABEL= ;;
present) export WORKSHOP_LABEL="training label" ;;
esac
/bin/sh -c '
if [ "${WORKSHOP_LABEL+x}" != x ]; then
printf "label is missing\n"
elif [ -z "$WORKSHOP_LABEL" ]; then
printf "label is present but empty\n"
else
printf "label is present and nonempty\n"
fi
'
done
)
label is missing
label is present but empty
label is present and nonempty
The three states are visible without redisplaying the dummy text. The parenthesized scope avoids changing the user's existing label. This technique does not require copying sensitive values to a shell variable in the prompt. Use an inspection hook inside the intended program's launch context when a production service needs a similar check. The success criterion is that the program receives and uses the setting through its approved source, with diagnostic output limited to its status.
Define how the receiving program interprets strings
An environment is a mapping of strings. Providing WORKSHOP_PREVIEW=false does not supply a Boolean value to every possible program. A script can treat the exact string false as disabled, or it can merely check whether the string has characters. The latter check considers false nonempty. Choose and document the accepted values. When a setting controls whether a command writes a file, explicitly recognizing both supported values makes the behavior clearer than trusting the human meaning of a string.
Use this small example to observe explicit parsing without writing any reports. The new shell checks two known values and supplies a safe default for absence. It treats a defined empty value as invalid, since the default expression omits the colon. All four invocations receive their own assignment. The loop stores no persistent state in your active shell and makes it easy to see which choices are accepted.
(
for value in true false '' maybe; do
WORKSHOP_PREVIEW="$value" /bin/sh -c '
case "${WORKSHOP_PREVIEW-false}" in
true) printf "preview only\n" ;;
false) printf "normal reporting mode\n" ;;
*) printf "invalid preview setting\n" >&2; exit 2 ;;
esac
'
printf 'status=%s\n' "$?"
done
)
preview only
status=0
normal reporting mode
status=0
invalid preview setting
status=2
invalid preview setting
status=2
Error lines go to stderr, so the combined display can interleave them differently. Use an ordinary demonstration shell without automatic exit on a failed command, or wrap each expected failure in an explicit conditional. Neither accepted value starts reporting work in this example. The point is the branch choice. To see the default path, launch the same command without the prefix from a shell where the name is unset. It prints normal reporting mode because absence uses the default false. Adding a colon to the expansion would make the empty value take that same branch. A setting with security or data integrity consequences may call for a different default, which should be part of the application design.
File paths and numeric settings need their own validation. A path written with a leading tilde inside a quoted value can reach an application as a literal tilde, depending on where and how it was assigned. An application must explicitly expand that value if it wants home-directory behavior. For this workshop use the literal path of the generated directory when supplying a location to the program. A port value such as 8123 arrives as four characters. The program must check whether it is an integer within the configured allowable range before it is used. Successful export only proves the parent stored a string.
When one value contains more than one component, choose a format that tells your program how to split it. PATH uses colons under the shell's rules. A list of display labels with user-supplied punctuation may need a structured file instead of another colon-separated string. On Unix an environment string cannot contain an embedded zero byte, so it is unsuitable for arbitrary binary data. Using a short text setting for a mode and a separately managed file for complex input makes the boundary easier to validate. Preserve one explicit test for every documented form your application accepts.
Trace an unexpected report label back to its source
Start the exercise with the original Python fixture if available. The mode file contains morning. Start the program with no matching variable in an isolated child and observe that it chooses the file. Run it with a prefix assignment of preview and observe that the environment wins. After it finishes, rerun without the assignment and verify that the mode returns to morning. Your record should show the source printed by the program as well as its value. Seeing preview once does not mean that the file was changed. Read the file afterward if you need independent confirmation.
For a second check, pose the opposite problem. The deployment says the application should use a file's label, but a child continues showing preview. Start one shell that exports the label and another process that independently uses the same file. If only the child of the first shell sees the override, draw the parent and child relationship. If a daemon's own logs still show the override, inspect its configured launch environment instead of unsetting a variable in your terminal. Identify whether the service needs a new invocation or dynamically reads a different configuration source. The observed behavior decides which source to review.
Now practice a nonsecret contradictory configuration. In the Python example, set the file to morning and the environment to an unavailable label such as evening. The mode validator should report an invalid mode from environment and return two. This shows that some applications deliberately reject unsupported values rather than falling through to another source. Restore a known allowed setting and run the test again. A planned change should include the expected result for a missing value, an empty value, an invalid value, and a valid one when those cases differ. This keeps a permissive fallback from masking a misconfigured production launch.
For the third test, compare PATH with the two fixture directories. Predict the results before reversing the order. Then explain why running the second file by its explicit path bypasses the lookup. In an approved script, you can choose an explicit program path when you know it, or define a short trusted search list when several standard tools are needed. For an interactive environment, a trusted directory at the end of the list is often enough when you want access to a new utility and do not intend to override an existing command. Test the actual selected program after any approved configuration edit.
Troubleshooting is easier when you keep evidence about the execution context. Write down the shell and its startup mode when a profile is involved. Note whether the setting appears only in that shell or is visible in a child. For a service, identify the actual manager and unit and read its documented input method. For a scheduled job, identify the table's account, interpreter, and input path. For a particular application, look up or test the order in which it takes its configured values. These checks narrow a problem without displaying environment data unrelated to the error.
If an application reads a string with spaces, preserve its boundaries when passing it to another tool. A double-quoted expansion like "$WORKSHOP_LABEL" supplies one value. An unquoted expansion can split into words and match wildcard characters depending on the shell and context. For example, an opening shift label passed to printf '%s\n' as one quoted argument prints as one line, while an unquoted two-word value can supply more arguments and produce more lines. Values and generated syntax require care at each boundary. Setting a value correctly in the environment is only the first boundary.
Most commands above isolate their shell changes automatically. The executable scripts, configuration file, and demonstration report are the only artifacts stored on disk. After confirming the generated path, remove the known files and empty directories. This does not edit any actual profile. Removing a local config file's name does not by itself clear a value already exported somewhere else. In this lab the explicit shell and process scopes already control that lifetime.
if [ -n "${env_lab:-}" ] && [ -d "$env_lab" ]; then
printf 'Cleaning fixtures from %s\n' "$env_lab"
rm -f -- "$env_lab/class-a/workshop-preview" "$env_lab/class-b/workshop-preview" \
"$env_lab/workshop.rc" "$env_lab/show-mode.py" "$env_lab/mode.txt"
rmdir -- "$env_lab/class-a" "$env_lab/class-b" "$env_lab/home" "$env_lab"
fi
unset env_lab
Check your understanding of the launch boundary
Interview question. What is the difference between assigning and exporting a variable?
Assignment creates or changes a value in the current shell. The export attribute tells that shell to put the named value into the environment for commands it launches. A setting already exported retains that attribute after an ordinary reassignment. A fresh child receives the values available at its launch time, and its own assignments need not affect the parent.
Interview question. How do you investigate a setting that is correct in a login shell but wrong in a system service?
Identify the manager, unit, account and application setting. Read the service's supported way of receiving that setting, verify its scope without exposing credentials, and test the actual service execution. Interactive startup files belong to the shell's launch sequence and are not automatically inputs to systemd.
Quiz. You run a script that exports WORKSHOP_MODE and exits. Why did your terminal keep its previous value?
The script ran in a child shell with its own copy of the environment. Its export affects only that process and descendants it starts. A trusted startup script loaded into the current shell can assign there, which is why reading it with the dot command behaves differently.
Quiz. Which expansion uses a default for an empty value as well as an absent one?
The form with the colon, ${NAME:-fallback}, checks both conditions. The form ${NAME-fallback} uses the fallback only if the variable is absent. Choose the form that matches the application's intended treatment of empty input.
Quiz. A file and a launch environment both set the mode. Which one wins?
Read the application or launcher's precedence rules. In this lesson's Python program an environment override wins, even when it is rejected as invalid. A different tool can choose an alternative priority. Confirm the source using a safe value and the application's actual behavior.
Revision cards
The child receives an initial copy
Exported settings travel to new processes. Changing one process's environment generally does not change another process that is already running.
The actual launcher supplies the inputs
Identify whether a terminal, scheduler, service manager or other launcher starts the program. Use the configuration method for that path.
Check presence carefully
Absent, empty, invalid, and valid values may have different effects. Inspect one nonsecret setting or its presence, and verify which source the program selected.
Primary references
- Linux description of process environment and inheritance
- Bash manual for export, startup files, search and expansion
- GNU coreutils env command and minimal environments
- Systemd execution environment and credential settings
- AWS CLI environment options and precedence
- AWS IAM roles and applications on EC2