worenga
worenga

Reputation: 5856

Bash command escaping quotes

I have the following bash snippet:

#as long as we read invalid stuff prompt the user
REPLY=
until [[ $REPLY =~ ^[YyNn]$ ]]; do
    read -p "Want to generate an Eclipse CDT4 Project? [y/n]" -n 1 -r
    echo    # (optional) move to a new line
done

PROJARGS=
if [[ $REPLY =~ ^[Yy]$ ]]
then
     PROJARGS='-G "Eclipse CDT4 - Unix Makefiles" -DCMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT=TRUE'
fi

cmake $PROJARGS -D CMAKE_BUILD_TYPE=$BUILD_TYPE ../src

Basically, I want to set additional $PROJARGS arguments whenever the user hits y.

However, the last port does not work since there are some quotes inserted, that i do not want to be there. Using set -x i found out that the following happens:

+ PROJARGS='-G "Eclipse CDT4 - Unix Makefiles" -DCMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT=TRUE'
+ cmake -G '"Eclipse' CDT4 - Unix 'Makefiles"' -DCMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT=TRUE -D CMAKE_BUILD_TYPE=Release ../src
CMake Error: Could not create named generator "Eclipse

So there are additional quotes inserted. I have no idea why. How do i prevent this?

Upvotes: 2

Views: 421

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46903

Don't put your arguments into a string! use an array!

projargs=()
if [[ $REPLY = [Yy] ]]; then
    projargs=( -G "Eclipse CDT4 - Unix Makefiles" -DCMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT=TRUE )
fi

(note I lowercased your variable, as uppercase variable names are considered bad practice in shell programming!).

Then use as:

cmake "${projargs[@]}" -D CMAKE_BUILD_TYPE="$BUILD_TYPE" ../src

(note the quotes).

As a sidenote, you don't need regexes here. A glob is enough:

until [[ $REPLY = [YyNn] ]]; do ...

More info and good practice in BashFAQ/050.

Upvotes: 1

Related Questions