0

I need a simple script to call gcc but I've got a long list of libraries that I need to pass to it in a directory who's path has a space on it.

In place of gcc for testing my script I've used:

#!/bin/bash
for var in "$@"
do
    echo "$var"
done

This is one of the umpteen attempts I've tried:

#!/bin/bash
LIBDIR="lib dir"
LIBS=
LIBS+="lib1 "
LIBS+="lib2 "
CMD="./debug.sh "
for LIB in $LIBS
do
    CMD+="-I ${LIBDIR}/${LIB} " 
done
${CMD}
exit

Obviously the problem is that bash cannot tell which spaces are meant to separate the arguments and which are not, but no matter how I place quotes or backslashes I cannot figure out how to 'quote' some of the spaces and not the others.

marked as duplicate by Michael Homer, Sparhawk, muru, Mr Shunz, X Tian Apr 11 at 17:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

For your particular case:

#!/bin/bash
LIBDIR="lib dir"
LIBS=("lib1" "lib2")
CMD=(./debug.sh)
for LIB in "${LIBS[@]}"
do
    CMD+=(-I "${LIBDIR}/${LIB}")
done
"${CMD[@]}"
exit

There are two arrays in use: LIBS for the library names, and CMD for the command itself. This will also work if there are other extra spaces. +=(...) concatenates the new items onto the end of an array, just like it concatenates the new string onto the end of a string. "${CMD[@]}" expands to all the values of the array as individual words (not split on spaces). Why does my shell script choke on whitespace or other special characters? has more on the subject in general, and How can we run a command stored in a variable? in the specific.

Not the answer you're looking for? Browse other questions tagged or ask your own question.