[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
cope with spaces in an environment variable
From: |
Masahiro Yamada |
Subject: |
cope with spaces in an environment variable |
Date: |
Mon, 19 Jun 2023 03:37:24 +0900 |
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
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
- cope with spaces in an environment variable,
Masahiro Yamada <=
- Re: cope with spaces in an environment variable, Davide Brini, 2023/06/18
- Re: cope with spaces in an environment variable, alex xmb ratchev, 2023/06/18
- Re: cope with spaces in an environment variable, Lawrence Velázquez, 2023/06/18
- Re: cope with spaces in an environment variable, Kerin Millar, 2023/06/18
- Re: cope with spaces in an environment variable, Kerin Millar, 2023/06/19
- Re: cope with spaces in an environment variable, Kerin Millar, 2023/06/19