-1

When running the command

cmake ../../ -DCMAKE_C_FLAGS="-DFOO -DBAR ${CMAKE_C_FLAGS}"

in bash, it works fine.

When passing through a script, it fails:

./myscript "-DFOO -DBAR"

cmake ../../ -DCMAKE_C_FLAGS="-DFOO -DBAR ${CMAKE_C_FLAGS}"
Parse error in command line argument: -DBAR

myscript:

#!/bin/bash
cmake_options='-DCMAKE_C_FLAGS="'$1' ${CMAKE_C_FLAGS}"'
echo "cmake ../../ "$cmake_options
cmake ../../ $cmake_options

I know it must be related to escaping characters somehow so I tried all I could (double/single quotes, backquotes, escaping backslashes, using $() etc.), but I couldn't find the fix...

I'm not a linux expert, could someone help me please?

PS: I'm working on cygwin but I tested on a regular Linux as well and the behaviour is the same.

EDIT:

@Assere as described, I already tried many things and changing from $1 to "$1" doesn't fix the issue. What I mean by "bash" is directly in the command prompt while what I mean by "sh" is the "myscript.sh" file. I do have a #!/bin/bash, I just didn't know it was called a shebang. I also tryed quoting $cmake_options, to no results.

Darkiwi
  • 227
  • 1
  • 4
  • 14
  • 1
    You should probably start by quotting `$1` like so : `"$1"` – Aserre Apr 04 '19 at 12:57
  • 1
    Also in your script you are running the `cmake` command in the folder `../../` whereas in the bash command you are running it against the `../../Sources` folder – Aserre Apr 04 '19 at 13:00
  • 1
    And why do you say there is a difference between `bash` and `sh` ? Is `sh` in the shebang of your script ? – Aserre Apr 04 '19 at 13:02
  • 1
    `sh` has nothing to do with calling a script directly. Do you have a special line at the begining of your script file ? If not, put the following code as the 1st line of your script : `#!/usr/bin/env bash`. This is called a shebang and specifies to linux which interpreter to use (here, it forces the use of `bash`) – Aserre Apr 04 '19 at 13:12
  • 1
    Also when you have spaces in your variable it is often crucial to quote them. Try quotting `$cmake_options` as `"$cmake_options"` everywhere in your script – Aserre Apr 04 '19 at 13:15
  • Storing shell syntax (like quotes) in a variable doesn't work; see ["Why does shell ignore quotes in arguments passed to it through variables?" ](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-shell-syntax-in-arguments-passed-via-variables) and [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050). Also, don't use `eval` -- it's a huge bug magnet. – Gordon Davisson Apr 04 '19 at 16:31

1 Answers1

1

use this script instead:

#!/bin/bash
cmake_options=-DCMAKE_C_FLAGS="\"$1 \${CMAKE_C_FLAGS}\""
echo "cmake ../../ "$cmake_options
cmake ../../ "$cmake_options"
Ali Hallaji
  • 3,712
  • 2
  • 29
  • 36