• Uncategorized

About bash : strange-variable-definition-in-shell-script

Question Detail

test.sh:

#! /bin/sh
me=I ./test2.sh

test2.sh:

#! /bin/sh
echo $me

run script 1 and printing this:

[[email protected] sh]$ ./test.sh
I
[[email protected] sh]$

As see, the variable “$me” be transferred to “test2.sh”.

I didn’t find this usage of variable definition on googling, can someone tell me where can find the tutorial including the usage above mentioned?

Thx a lot!

Question Answer

Since this has been mentioned on SO a lot, I’m assuming you’re looking for some documentation on it. I’m not sure there is anything more detailed than the BASH documentation about this:

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.

As you’ve seen by experimenting, when you do “A=B command”, it runs the command as if “export A=B” was run just prior to that command then A’s value reverts to its previous after command completes. It’s a very convenient way to pass some environment into a command while ensuring the rest of the script is not affected.
……………………………………………………
From the bash documentation on the Environment:

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.

So if you put variable assignments before a command, that command is run with those environment variables.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.