[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Doesn't MY_ENV=abc printf "${MY_ENV}\n" suppose to print abc?

On Sat, August 02 at 12:08 PM EDT
Dave Carrigan <dave@rudedog.org> wrote:

>On Sat, Aug 02, 2003 at 08:49:36PM +0300, Shaul Karl wrote:
>>   According to my understanding of the manual page,
>>     $ MY_ENV=abc printf "${MY_ENV}\n"
>> Should have print abc. But it does not:
>>     $ MY_ENV=abc printf "${MY_ENV}\n"
>> What am I missing?
>The "MY_ENV=abc printf" syntax sets the environment variable for the
>printf subprocess. And, in fact, when printf runs, MY_ENV is truly set
>to abc. However, the "${MY_ENV}\n" is expanded *before* printf is
>executed, and since MY_ENV is not set in the existing shell, the
>expansion results in an empty string. The printf command doesn't even
>see MY_ENV in its arguments, all it sees is a single argument that
>looks like ``\n''.

Can you elaborate a little more on this?  I am curious, too.  After
reading your email I tried this:
slamson@callerio:~$ unset COMMAND
slamson@callerio:~$ COMMAND="printf" $COMMAND "x${COMMAND}\n"
bash: x\n: command not found
slamson@callerio:~$ COMMAND="printf" && $COMMAND "x${COMMAND}\n"

So it seems that the variable is not assigned even for the subprocess. 
Does the shell see programs to execute before it looks to do variable
substitution?  I know the first things it sees are pipes and redirects
but I don't know more.

I must admit I had never thought of just running a command
after an assignment so it has never come up. "Bug hunting" is great, but
if the OP needs a solution for something, what about this:
slamson@callerio:~$ unset MY_ENV slamson@callerio:~$ (MY_ENV=abc &&
printf "x${MY_ENV}\n") xabc
slamson@callerio:~$ echo x$MY_ENV

The parens make a subshell which is the "new environment" I assume the
the man page is talking about, right?

Thank you,

Shawn Lamson

Reply to: