Skip to content

Instantly share code, notes, and snippets.

@sebnyberg
Last active March 25, 2022 15:58
Show Gist options
  • Save sebnyberg/21ab8e31dcad822247a6f2e7ef6d0b82 to your computer and use it in GitHub Desktop.
Save sebnyberg/21ab8e31dcad822247a6f2e7ef6d0b82 to your computer and use it in GitHub Desktop.
Unintuitive Bash behavior for variables

Setting a local variable then running a command does not provide the variable to the child process:

$ GREETING=hi
$ python3 -c 'import os; print(os.environ.get("GREETING", "unknown"))'
unknown

However, setting a local variable in the same statement as the command does:

$ GREETING=hi python3 -c 'import os; print(os.environ.get("GREETING", "unknown"))'
hi

Exporting the variable is guaranteed to work, either with export

$ export GREETING=hi
$ python3 -c 'import os; print(os.environ.get("GREETING", "unknown"))'
hi

...or with set -o allexport.

$ set -o allexport
$ GREETING=hi
$ python3 -c 'import os; print(os.environ.get("GREETING", "unknown"))'
hi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment