Quoting is always a pain in the neck. In order to understand it, you have to understand what happens at each level of the processing.
Thankfully, in a script, Keyboard Maestro itself does not do any processing, so that is one less place for confusion.
With shell commands, the important thing to understand is that, with only a few exceptional programs, it is not the command that does the processing, it is the shell (bash usually, although there are many shells).
So it is the bash tool that sees the string
defaults write /Users/me/Library/Application\ Support/Witch/Settings $KMVAR_witchPref
and it processes it in to an array of strings which it passes to the defaults tool. This is important - the defaults command receives not a single string, but an array of strings:
- defaults
- write
- /Users/me/Library/Application Support/Witch/Settings
- "Selection
- Style"
- -int
- 0
Note that it is bash that has processed the variable substitution for $KMVAR_witchPref, split the line in to seven parts, processed the backslash in "Application\ Support" and then executed the defaults tool with the seven parts as arguments (the command itself is the 0th argument, normally mostly ignored by tools).
So the problem is that the variable substitution, backslash, de-quoting is all happening at the start, after which you are left with quotes from the variable substitution, but they no longer have any meaning, they are just characters.
As for the best way to solve this, well, I would generally have two or even three parts:
defaults write "/Users/me/Library/Application Support/Witch/Settings" "$KMVAR_Setting" -"$KMVAR_Type" "$KMVAR_Value"
Rather than a string representing three pieces of information.