env variables with spaces

Brad De Vries devriesbj
Wed Feb 28 06:20:56 PST 2007


On 2/27/07, Bill Campbell <linux-sxs at celestial.com> wrote:
> On Tue, Feb 27, 2007, Net Llama! wrote:
> >I'm running into an annoying problem.  I'm taking the output from 'env'
> >and dumping it to a file (/tmp/env.out), and then running 'source
> >/tmp/env.out'.  The problem is that some of the variables in env output
> >have values assigned to them with spaces, such as:
> >FOO=release debug
> >
> >When source hits this, it gets confused and assumes that the ' debug'
> >portion is something separate from the value of FOO, and barfs:
> >bash: release: command not found
> >
> >Anyone have any suggestions how to get around this?  thanks
>
> Wrap all variables in double quotes.
>
> env | sed 's/=\(.*\)/="\1"/' > /tmp/env.out
> . /tmp/env.out
>
> This doesn't take care of escaping double quotes in the value of
> the variables.  That's left as an exercise for the student.
>
> A safer way might be:
>
> #!/usr/bin/env python
> import os, sys
> for k, v in os.environ.items:
>     print '%s=%s' % (k, repr(k))
> sys.exit(0)
>
> Bill
> --
> INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software, LLC
> URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
> FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
>
> ``But how is this legal plunder to be identified? Quite simply. See if the
> law takes from some persons what belongs to them, and gives it to other
> persons to whom it does not belong. See if the law benefits one citizen at
> the expense of another by doing what the citizen himself cannot do without
> committing a crime.'' -- Frederic Bastiat, The Law

I like Bill's second approach, the python script, because:
1) a variable's value might span multiple lines, i.e., have new-lines embedded.
2) a variable's value might contain embedded quotes.  You'd have to
add some logic to the python script to escape the embedded quotes, but
it'd be a lot easier than adding it to the sed script.

Brad.



More information about the Linux-users mailing list