Bash – Invoking a command line with spaces from a variable in a Bash script

bash

I thought it would be easy, but I already wasted a few hours on this.

I want to run the following CMake command from inside a Bash script. In a terminal I would type

cmake -G "Unix Makefiles" .

and it works. If I copy this exactly inside the Bash script it works as well.

But the script is meant to work on multiple platforms, and it could be "MSYS Makefiles" instead of "Unix Makefiles". Therefore, I want to put the command in a variable, where the contents depends on the platform and execute it. However, this is where I got stuck. I tried every combination of single/double quotes I could think of, but I got nowhere.

I want something along the lines

c="cmake . -G \"Unix Makefiles\""
exec $c

but it always results in some variation of the following:

CMake Error: Could not create named generator "Unix

I realize that I could do

if test [... this is Unix ...]
    cmake . -G "Unix Makefiles"
else
    cmake . -G "MSYS Makefiles
fi

but since this call has to be made several times I'd rather avoid it.

Any suggestion?

Best Answer

It is best not to use eval unnecessarily. Try not to put the command inside a variable. You can put the options as a variable though:

if [ ... ]
  string="Unix makefiles"
else
  string="MSYS Makefiles"
else
  string="...."
fi
cmake -G "$string" # Just call the command normally