-7

Why do the following examples from Arrow's reply output $var instead of 3?

I single quote or backslash $var as '$var' or \$var, hoping that

  • first $var will be passed literally into the execution environment of the executable program /bin/echo, and
  • then inside the execution environment of the executable program /bin/echo, the environment variable var=3 applies when parameter expansion happens on $var.

Why doesn't the parameter expansion happen inside the execution environment of the executable program /bin/echo? Note:

  • in the original shell, $var is single quoted or backslashed, so should not be expanded in the execution environment of the original shell.

  • the original shell removes the single quotes or backslash around $var, and then passes $var and environment variable var=3 into the execution environment for running /bin/echo, so I think that parameter expansion of $var should happen in the execution environment for running /bin/echo.

Note that I use set -x to print out the trace information, but can't figure out what is actually the result after expansion but before execution.

Thanks.

tim$ unset var $ set -x tim$ var=3 /bin/echo '$var' + var=3 + /bin/echo '$var' $var tim$ var=3 /bin/echo \$var + var=3 + /bin/echo '$var' $var $ var=3 exec /bin/echo \$var | cat + cat + var=3 + exec /bin/echo '$var' $var tim$ var=3 exec /bin/echo '$var' | cat + var=3 + exec /bin/echo '$var' + cat $var 
2
  • 1
    mywiki.wooledge.org/Quotes Commented Aug 8, 2017 at 19:15
  • 2
    Why would /bin/echo know or care about variable expansion? Variable expansion is a shell feature, not a property of the environment. Commented Aug 8, 2017 at 19:38

1 Answer 1

5

In every single case, you are either strong-quoting, which prevents expansion of the variable; or escaping the $ character, which also makes it no longer a variable subject to expansion. /bin/echo and cat doesn't do any parameter or variable expansion whatsoever, so piping into it would not cause such to occur.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.