Skip to content

Files

Latest commit

 

History

History
41 lines (26 loc) · 1.32 KB

SC2097.md

File metadata and controls

41 lines (26 loc) · 1.32 KB

Pattern: Bash assignment is only seen by the forked process

Issue: -

Description

In name=World cmd "$name", name=World is passed in as part of the environment to cmd (i.e., in the envp parameter to execve(2)). 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.

Example of incorrect code:

name=World cmd -m "Hello $name"

Example of 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

Exceptions

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.

Further Reading