Setting an argument with bash

2018-12-31 16:56发布

问题:

I frequently run a simple bash command:

rpm -Uvh --define \"_transaction_color 3\" myPackage.rpm

which works properly.

But now I\'m trying to script it into a bash file, and make it more flexible:

#!/bin/bash
INSTALL_CMD=rpm
INSTALL_OPT=\"-Uvh --define \'_transaction_color 3\'\"

${INSTALL_CMD} ${INSTALL_OPT} myPackage.rpm

However, this keeps generating the error:

error: Macro % has illegal name (%define)

The error is coming from how --define and the quoted _transaction_color is handled.
I\'ve tried a variety of escaping, different phrasing, even making INSTALL_OPT an array, handled with ${INSTALL_OPT[@]}.

So far, my attempts have not worked.
Clearly, what I want is extremely simple. I\'m just not sure how to accomplish it.

How can I get bash to handle my --define argument properly?

回答1:

The problem is that quotes are not processed after variable substitution. So it looks like you\'re trying to define a macro named \'_transaction_color.

Try using an array:

INSTALL_OPT=(-Uvh --define \'_transaction_color 3\')

then:

\"$INSTALL_CMD\" \"${INSTALL_OPT[@]}\" myPackage.rpm

It\'s important to put ${INSTALL_OPT[@]} inside double quotes to get the requoting.



回答2:

It might be a bash issue with word splitting on space:

Try:

#!/bin/bash

IFS=$\'\\n\'

INSTALL_CMD=rpm
INSTALL_OPT=\'-Uvh\'
INSTALL_OPT_DEFINE=\'--define _transaction_color 3\'

${INSTALL_CMD} ${INSTALL_OPT} ${INSTALL_OPT_DEFINE} myPackage.rpm


标签: linux bash unix