1

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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).

2 Comments

How is that safer than using eval? If $COMPOPT is set to rm -rf /; , it will still get executed, no?
No I never claimed on safety, writing shell script has its own risk if one is not careful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.