harish
harish

Reputation: 1924

Passing bash variable to make without extra single quotes

I am trying to pass additional flags to make with bash variable if the software version contains specific version string. However bash expansion seems to add additional single quotes causing make to throw an error.

if  [[ $SW_VER == *"v2.0.1"* ]] ;
then
  ADDITIONAL_FLAGS="CFLAGS=\"-DFLAG1 -DFLAG2\""
else
  ADDITIONAL_FLAGS=""
fi
make "$ADDITIONAL_FLAGS"

With -x option in script I see that it expands as below.

+ ADD_FLAGS='CFLAGS="-DFLAG1 -DFLAG2"'

How to avoid the single quotes above? Below is what is actually intended.

make CFLAGS="-DFLAG1 -DFLAG2"

Upvotes: 1

Views: 185

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80921

-x adds single quotes to identify "words" in its output they aren't really there.

That being said the internal double quotes are actually there and that's a problem (the shell won't remove them so they will end up in the value of CFLAGS).

You want to drop them entirely.

ADDITIONAL_FLAGS="CFLAGS=-DFLAG1 -DFLAG2"

Example to illustrate the single quotes of set -x and the problem with the internal double quotes:

$ c ()
{
    printf 'argc: %s\n' "$#";
    printf 'argv: %s\n' "$@"
}
$ c arg1 'arg2 arg3' arg4 # Example of c function usage and behavior.
argc: 3
argv: arg1
argv: arg2 arg3
argv: arg4
$ set -x
$ ADDITIONAL_FLAGS="CFLAGS=\"-DFLAG1 -DFLAG2\""
+ ADDITIONAL_FLAGS='CFLAGS="-DFLAG1 -DFLAG2"'
$ echo "$ADDITIONAL_FLAGS"
+ echo 'CFLAGS="-DFLAG1 -DFLAG2"'
CFLAGS="-DFLAG1 -DFLAG2"
# See how the single quotes are only in the set -x output there?
$ c "$ADDITIONAL_FLAGS"
+ c 'CFLAGS="-DFLAG1 -DFLAG2"'
+ printf 'argc: %s\n' 1
argc: 1
+ printf 'argv: %s\n' 'CFLAGS="-DFLAG1 -DFLAG2"'
argv: CFLAGS="-DFLAG1 -DFLAG2"
# See how the internal double quotes are in the actual argument value?
$ ADDITIONAL_FLAGS="CFLAGS=-DFLAG1 -DFLAG2"
+ ADDITIONAL_FLAGS='CFLAGS=-DFLAG1 -DFLAG2'
$ echo "$ADDITIONAL_FLAGS"
+ echo 'CFLAGS=-DFLAG1 -DFLAG2'
CFLAGS=-DFLAG1 -DFLAG2
$ c "$ADDITIONAL_FLAGS"
+ c 'CFLAGS=-DFLAG1 -DFLAG2'
+ printf 'argc: %s\n' 1
argc: 1
+ printf 'argv: %s\n' 'CFLAGS=-DFLAG1 -DFLAG2'
argv: CFLAGS=-DFLAG1 -DFLAG2

Upvotes: 2

candymanuu
candymanuu

Reputation: 110

try

if  [[ $SW_VER == *"v2.0.1"* ]] ;
then
  ADDITIONAL_FLAGS='CFLAGS="-DFLAG1 -DFLAG2"'
....

Upvotes: 0

Related Questions