malat
malat

Reputation: 12499

Properly splitting a string in UNIX shell

I need to be able to split a string so that each string are passed as variable in my shell.

I tried something like this:

$ cat test.sh
#!/bin/sh

COMPOPT="CC=clang CXX=clang++"
$COMPOPT cmake ../gdcm

I also tried a bash specific solution, but with no luck so far:

$ cat test.sh
#!/bin/bash -x

COMPOPT="CC=clang CXX=clang++"
ARRAY=($COMPOPT)
"${ARRAY[0]}" "${ARRAY[1]}" cmake ../gdcm

I always get the non-informative error message:

./test.sh: 5: ./t.sh: CC=clang: not found

Of course if I try directly from the running shell this works:

$ CC=clang CXX=clang++ cmake ../gdcm

Upvotes: 1

Views: 93

Answers (3)

chepner
chepner

Reputation: 531075

Another eval-free solution is to use the env program:

env "${ARRAY[@]}" cmake ../gdm

which provides a level of indirection to the usual FOO=BAR command syntax.

Upvotes: 2

anubhava
anubhava

Reputation: 785098

Though devnull's answer works but uses eval and that has known pitfalls.

Here is a way it can be done without invoking eval:

#!/bin/sh

COMPOPT="CC=clang CXX=clang++"
sh -c "$COMPOPT cmake ../gdcm"

i.e. pass the whole command line to sh (or bash).

Upvotes: 1

devnull
devnull

Reputation: 123458

When you say:

$COMPOPT cmake ../gdcm

the shell would attempt to execute the value of the variable as a command.

The evil eval is rather handy in such cases. Say:

eval $COMPOPT cmake ../gdcm

Upvotes: 1

Related Questions