Shell variables stay local until they are exported. Exported names become environment variables for child processes.

Program

Play the script to choose a profile, export it, and read it from a child shell.

profile
export_child_env.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

profile="dev"
export APP_PROFILE="$profile"
child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')
echo "child=$child_value"
#!/usr/bin/env bash

profile="test"
export APP_PROFILE="$profile"
child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')
echo "child=$child_value"
#!/usr/bin/env bash

profile="prod"
export APP_PROFILE="$profile"
child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')
echo "child=$child_value"
  1. profile ← dev

    3profile="dev"4export APP_PROFILE="$profile"
    values this stepdevprofile
  2. APP_PROFILE ← dev, exported ← APP_PROFILE

    3profile="dev"4export APP_PROFILE="$profile"5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')
    values this stepdevAPP_PROFILEAPP_PROFILEexporteddevprofile
  3. child_value ← dev

    4export APP_PROFILE="$profile"5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')6echo "child=$child_value"
    values this stepdevchild_valuedevAPP_PROFILE
  4. echo "child=$child_value"

    5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')6echo "child=$child_value"
    outputchild=dev
    values this stepdevchild_value
  1. profile ← test

    3profile="test"4export APP_PROFILE="$profile"
    values this steptestprofile
  2. APP_PROFILE ← test, exported ← APP_PROFILE

    3profile="test"4export APP_PROFILE="$profile"5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')
    values this steptestAPP_PROFILEAPP_PROFILEexportedtestprofile
  3. child_value ← test

    4export APP_PROFILE="$profile"5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')6echo "child=$child_value"
    values this steptestchild_valuetestAPP_PROFILE
  4. echo "child=$child_value"

    5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')6echo "child=$child_value"
    outputchild=test
    values this steptestchild_value
  1. profile ← prod

    3profile="prod"4export APP_PROFILE="$profile"
    values this stepprodprofile
  2. APP_PROFILE ← prod, exported ← APP_PROFILE

    3profile="prod"4export APP_PROFILE="$profile"5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')
    values this stepprodAPP_PROFILEAPP_PROFILEexportedprodprofile
  3. child_value ← prod

    4export APP_PROFILE="$profile"5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')6echo "child=$child_value"
    values this stepprodchild_valueprodAPP_PROFILE
  4. echo "child=$child_value"

    5child_value=$(bash -c 'printf "%s" "$APP_PROFILE"')6echo "child=$child_value"
    outputchild=prod
    values this stepprodchild_value
export `export NAME=value` places a shell variable into the environment.
child process A child shell inherits exported variables from the parent shell.
local variable Without export, ordinary shell variables are not part of the child environment.