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: alex xmb ratchev
Subject: Re: cope with spaces in an environment variable
Date: Sun, 18 Jun 2023 21:12:07 +0200

On Sun, Jun 18, 2023, 20:38 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}?
>
>
> Here are two prerequisites:
>
> [1] The compiler installation path may contain spaces.
> For example, if the compiler is located in '/tmp/a b/',
>
>  export CC="'/tmp/a b/gcc'"
>
> [2] The 'CC' may not be a single word.
>     If ccache is used, it can be two words.
>
>   export CC="ccache gcc"
>
>
>
> If it were Makefile, the code would be very simple.
>
>   all:
>            $(CC) helloworld.c
>
>
>
> If you try to do something equivalent in a shell script,
> it looks more complex.
>
>
> Ans1)
>
>   #!/bin/sh
>   "${CC}" helloworld.c
>
>
> This does not work with [2].
>
>   $ export CC="ccache gcc"
>   $ ./build-helloworld.sh
>   ./build-helloworld.sh: 2: ccache gcc: not found
>

quote when needed to preserve , no quote to make shell interpret it to some
part
in this case no quote

.. the eval topic ..
i got a lightier version , i heard not so secure either
using that bash parses builtin ( declare in my case ) strings

flat='ccache gcc "a b c".c'
declare -a "exp=( $flat )"
declare -p exp

declare -a exp=([0]="ccache" [1]="gcc" [2]="a b c.c")

for use like

"${exp[@]}"

.. as cmd .. like just this on a line .. where it will execute ..


Ans2)
>
>   #!/bin/sh
>   ${CC} helloworld.c
>
> This works with [2], but not [1].
>
>   $ export CC="'/tmp/a b/gcc'"
>   $ ./build-helloworld.sh
>   ./build-helloworld.sh: 2: '/tmp/a: not found
>
>
> Ans3)
>
>   #!/bin/sh
>   eval "${CC} helloworld.c"
>
> This works with [1], [2], and the combination of them.
>
>   $ mkdir -p '/tmp/a b'
>   $ ln -s /usr/bin/gcc '/tmp/a b/gcc'
>   $ export CC="ccache '/tmp/a b/gcc'"
>   $ ./build-helloworld.sh
>
>
> So, using 'eval' seems to work for me, but
> it is somewhat tedious to repeat 'eval' in each line
> that uses ${CC}.
>
> Is this a proper way, or is there a better way?
>
>
> --
> Best Regards
> Masahiro Yamada
>
>


reply via email to

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