env variables with spaces
Bill Campbell
linux-sxs
Wed Feb 28 12:47:35 PST 2007
On Wed, Feb 28, 2007, Brad De Vries wrote:
>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)
>>
...
>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.
The ``repr(k)'' handles quoting quotes properly, although it may
not always use single quotes around the whole expression, but use
double quotes which would cause problems with the shell expansion
of backwhacked characters.
I wrote an sqlrepr(s) function in python to handle this type of
problem when creating strings for SQL commands, wrapping the
string with single quotes. As a side effect this can also be
used nicely for this type of problem.
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
Imagine if every Thursday your shoes exploded if you tied them the usual
way. This happens to us all the time with computers, and nobody thinks of
complaining.
-- Jef Raskin http://jefraskin.com/
More information about the Linux-users
mailing list