Mabedan Mabedan - 4 months ago 6
Bash Question

How to run commands using variables which included quotes, in bash?

I'm trying to run a command while injecting a variable which has quotes, but bash keeps adding extra quotes which I don't need and falsifies the process...

this is my example:

set -x
MYVAR=" --name='user should login' "
cucumber $MYVAR

this results into running this:

cucumber '--name='\''user' should 'login'\'''

and the command fails. However, when I run
cucumber --name='user should login'
as is, without using variables, everything goes as expected.

PS. same result with
cucumber "${MYVAR}"
cucumber "$MYVAR"


It is better to use BASH arrays for storing command lines:

myvar=(--name 'user should login')
cucumber "${myvar[@]}"

I've also lowercased your variable as using all UPPER case variables can be problematic sometimes.