Reputation: 3024
Suppose I have a bat
(or cmd
) script that sets an environment variable:
rem set_foo.bat
SET foo=XXX
I want to call that script from a Cygwin bash script, in such a way that the variable set by set_foo.bat
is visible by the Cygwin bash script. That is, this Cygwin bash script:
#!/bin/sh
<call set_foo.bat in such a way that FOO becomes visible to this Cygwin script>
echo FOO is ${FOO}
should print:
FOO is XXX
Is this possible, and how?
PS 1: I am aware of the solutions proposed here: cygwin environment variables set in bat file, and they are NOT what I want.
PS 2: The bat script is not under my control (the Cygwin bash script is), so any solution that involves tweaking the bat script is not acceptable.
PS 3: If I just call set_foo.bat
from the Cygwin bash script like this:
#!/bin/sh
set_foo.bat
echo FOO is ${FOO}
then the value of FOO
is not visible. That is, the Cygwin bash script prints:
FOO is
Upvotes: 3
Views: 782
Reputation: 898
Here is a simple working example. Make a cygwin
shell script (with LF for EOL)
:
# runner.sh
cmd=/cygdrive/c/Windows/system32/cmd.exe
$cmd /C wrapper.bat
diff env0.txt env1.txt | dos2unix | sed -e '/[0-9]/d' -e '/^> /s/> //'
and a cmd script (with CR/LF for EOL)
@rem wrapper.bat
@set > env0.txt
@call .\set_foo.bat
@set > env1.txt
and a stand-in for the original cmd file (also with CR/LF for EOL)
@rem set_foo.bat
@set FOO=BAZ
Executing ./runner.sh
from the shell will display environment variables set by the set_foo.bat
cmd file. As long as that file does not use the setlocal
command, you will see all environment changes in wrapper.bat
. This should display new environment variables properly. Handling deletes or changes is left as an excercise for the reader, likewise passing in arguments.
HTH
Upvotes: 0
Reputation: 24476
Try this:
#!/bin/sh
export $(cmd /c "set_foo.bat & set foo" | grep "^foo=")
echo Foo is $foo
As long as set_foo.bat
doesn't set the value of %foo%
within a setlocal
scope, the value should carry over to the & set foo
half of the cmd.exe
-interpreted command. That will output the variable=value pair, which export
will interpret as a native variable assignment.
Upvotes: 2