2

i want to put some arguments into a variable f.e.

CFLAGS=-c --sysroot=$sysroot

but bash complains that it does not find the file --sysroot... why? How can I put this arguments into the variable and pass them later to the program.

Additionally i would like to do something like:

for dir in ${include_dirs[*]};
do
    CFLAGS=$CFLAGS "-I$dir"
done

but this does also not work as expected.

EDIT: One solution

CFLAGS=("-c" "--sysroot=$sysroot")

and in the loop

CFLAGS=("${CFLAGS[0]}" "-I$dir")

i am wondering if there is maybe a more obvious solution.

Daniel Bişar
  • 2,663
  • 7
  • 32
  • 54
  • What is the `...` part after the `--sysroot` error? – beroe Mar 30 '14 at 17:43
  • The other parts i added to the variable – Daniel Bişar Mar 30 '14 at 17:55
  • You almost had it right the first time. Only 2 changes necessary. `CFLAGS="-c --sysroot==$sysroot"` and in the loop `CFLAGS="$CFLAGS -I$dir"`. Your original post breaks in both places due to spaces while assigning value to variable. By enclosing the space within the quotes, the problem is fixed. – alvits Mar 30 '14 at 18:27

1 Answers1

4

In shell quotes are pretty important so:

CFLAGS="-c --sysroot=$sysroot"

otherwise BASH interprets it as 2 different argument.

Alternatively you can use arrays to store it:

CFLAGS=("-c" "--sysroot=$sysroot")

And use them later as:

"${CFLAGS[@]}"

very important to quote the array expansion.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • If i do CFLAGS="-c --sysroot=$sysroot" execute the loop and call gcc $CFLAGS it outputs unknown argument "-c --sysroot...." and if i do the second suggestion, the loop will not work. – Daniel Bişar Mar 30 '14 at 17:46
  • 1
    for more details: [I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050) – glenn jackman Mar 30 '14 at 18:24