From 40a3204ca806486a18ec3b01b4b1358c9f755cf8 Mon Sep 17 00:00:00 2001 From: koalaman Date: Mon, 3 Mar 2014 19:20:43 -0800 Subject: [PATCH] Created SC2097 (markdown) --- SC2097.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 SC2097.md diff --git a/SC2097.md b/SC2097.md new file mode 100644 index 0000000..3aec01b --- /dev/null +++ b/SC2097.md @@ -0,0 +1,29 @@ +## This assignment is only seen by the forked process. + +### Problematic code: + + name=World cmd -m "Hello $name" + +### Correct code: + + export name=World + cmd -m "Hello $name" + +To prevent setting the variable, this can also be done in a subshell: + + ( + export name=World + cmd -m "Hello $name" + ) # 'name' does not leave this subshell + +### Rationale: + +In `name=World cmd "$name"`, `name=World` is passed in as part of the environment to `cmd` (i.e., in the `envp` parameter to [man 2 execve](http://linux.die.net/man/2/execve)). This means that `cmd` and its children will see the parameter, but no other processes will. + +However, `"$name"` is not expanded by `cmd`. `"$name"` is expanded by the shell before `cmd` is ever executed, and thus it will not use the new value. + +The solution is to set the variable and export the variable first. If limited scope is desired, a `( subshell )` can be used. + +### Contraindications + +In the strange and fabricated scenarios where the script and a program uses a variable name for two different purposes, you can ignore this message. This is hard to conceive, since scripts should use lowercase variable names specifically to avoid collisions with the environment. \ No newline at end of file