source bash config from perl code
Oleg Goldshmidt
pub at goldshmidt.org
Fri Oct 2 11:33:52 IST 2009
Noam Meltzer <tsnoam at gmail.com> writes:
> On Thu, Oct 1, 2009 at 12:57 PM, Tzafrir Cohen <tzafrir at cohens.org.il> wrote:
>
> 3. You still need to export the variables to make them
> available in the
> environment of the shell script:
>
> export $EXPORTED_VARS
>
> Well, not necessarily.
> At least in bash (I didn''t check /bin/sh), you can use 'set -a' to
> automatically mark variables and functions which are modified or created for
> export to the environment of subsequent commands. (so knowing the variables
> ahead is not a must)
OK, as long as we are on this design review, I must be missing
something. The config.env script, if it does what it is supposed to do
(set the environment), should export what should be exported. If it
doesn't, I don't understand what the intent is.
Since it is sourced the exports work in the context of the wrapper
script, and child processes will inherit the environment. So will
exec, unless used with -c, but exec is really unnecessary here (saving
a process table entry is a weak excuse, and it may complicate error
handling - read up on execfail, etc.).
What is missing from this design review is error handling, e.g., what
happens if sourcing config.env fails, etc. (I mentioned it in an
earlier post).
A skeleton "withenv" script can look as follows (UNTESTED)
---------------------------------------
#!/bin/bash
function die() {
echo "$2" > /dev/stderr
exit $1
}
# are we sane?
test $# -gt 1 || die 1 "Usage: $0 <env> <command line>"
# the 1st argument prepares the environment
environment=$1
shift
# no need for further checking - source will catch any errors related
# to the file existence, permissions, etc.
source $environment
rc=$?
test $rc -eq 0 || die $rc "Failed to source $environment, exiting"
# now run the rest of the command line
$@
----------------------------------
Note that a command line that refers to environment variables will
expand them before the $environment is sourced.
--
Oleg Goldshmidt | pub at goldshmidt.org
More information about the Linux-il
mailing list