Why doesn't foo=bar echo "$foo" print bar?
This is subtle, and has to do with the exact order in which the BashParser performs each step.
Many people, when they first learn about var=value command and how it temporarily sets a variable for the duration of a command, eventually work up an example like this one and become confused why it doesn't do what they expect.
As an illustration:
$ unset foo $ foo=bar echo "$foo" $ echo "$foo" $ foo=bar; echo "$foo" bar
The reason the first one prints a blank line is because of the order of these steps:
The parameter expansion of $foo is done first. An empty string is substituted for the quoted expression.
After that, Bash sets up a temporary environment and puts foo=bar in it.
The echo command is run, with an empty string as an argument, and foo=bar in its environment. But since echo doesn't care about environment variables, it ignores that.
This version works as we expect:
$ unset foo $ foo=bar bash -c 'echo "$foo"' bar
In this case, the following steps are performed:
A temporary environment is set up with foo=bar in it.
bash is invoked within that environment, and given -c and echo "$foo" as its two arguments.
The child Bash process expands the $foo using the value from the environment and hands that value to echo.
It's not entirely clear, in all cases, why people ask us this question. Mostly they seem to be curious about the behavior, rather than trying to solve a specific problem; so I won't try to give any examples of "the right way to do things like this", since there's no real problem to solve.