help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: cope with spaces in an environment variable


From: Kerin Millar
Subject: Re: cope with spaces in an environment variable
Date: Mon, 19 Jun 2023 10:57:47 +0100

On Mon, 19 Jun 2023 10:51:08 +0100
Kerin Millar <kfm@plushkava.net> wrote:

> On Mon, 19 Jun 2023 12:09:35 +0900
> Masahiro Yamada <masahiroy@kernel.org> wrote:
> 
> > On Mon, Jun 19, 2023 at 4:22 AM Kerin Millar <kfm@plushkava.net> wrote:
> > >
> > > On Mon, 19 Jun 2023 03:37:24 +0900
> > > Masahiro Yamada <masahiroy@kernel.org> wrote:
> > >
> > > > Hi.
> > > >
> > > > I'd like to know the proper handling of an environment variable
> > > > when the value may contain spaces (with quoting).
> > > >
> > > > Here is my question.
> > > >
> > > > You have the environment variable 'CC', which contains a compiler path.
> > > >
> > > > For example, how to write a shell script to
> > > > compile a C file with ${CC}?
> > >
> > > By shell script, do you mean that POSX sh is the intended target?
> > 
> > 
> > Thanks for the pointers, all guys.
> > 
> > 
> > 
> > Ideally, working on POSIX sh would be nice.
> 
> If I had to do this, I would not be inclined to use eval. Greg has already 
> stressed this point. The least-bad options (by my reckoning) are shown below.
> 
> # Parse newline-separated arguments out of a string. No shell code injection.
> # Obviously, it cannot support arguments containing newlines. Allows for the
> # positional parameters to be preserved, though this example does not.
> printf '%s\n' "$CC_ARGS" | {
>       set -- cc
>       while IFS= read -r word; do
>               set -- "$@" "$word"
>       done
> 
>       "$@" foo.c
> }
> 
> # Let xargs(1) do the parsing. Requires understanding - and acceptance - of
> # the behaviour of its parser, along with its limitations. Has rudimentary
> # quote handling. Tolerable for simple cases, where its input is tightly 
> # controlled and predictable in advance. Doesn't scale beyond that. No code
> # injection either. Makes it a little more expensive to call cc.
> CC() {
>       printf %s "$CC_ARGS" | xargs -E '' cc
> }
> 
> CC foo.c

Well, I should have known better than to post before my first infusion of 
caffeine. Of course, the second example should have invoked xargs in the 
fashion of xargs -E '' cc "$@". This probably isn't viable as the arguments 
parsed from CC_ARGS will then follow "foo.c" rather than precede it. For that, 
there is no adequate solution.

-- 
Kerin Millar



reply via email to

[Prev in Thread] Current Thread [Next in Thread]