Pass string variable as string literal in bash

Viewed 38

I am trying to pass a string-valued variable as a literal string in bash:

TEXT='Esto concuerda con la observación de Hord, que afirma que las espinacas contienen mucha vitamina K, lo que ayuda a reducir la presión arterial y el riesgo de sufrir enfermedades cardiovasculares.'

python normalize.py \
    --text $TEXT \
    --language es \
    --cache_dir ./es_norm_cache_dir/

The script normalize.py expects a string, so the above should expand to:

python normalize.py \
    --text 'Esto concuerda con la observación de Hord, que afirma que las espinacas contienen mucha vitamina K, lo que ayuda a reducir la presión arterial y el riesgo de sufrir enfermedades cardiovasculares.' \
    --language es \
    --cache_dir ./es_norm_cache_dir/

i.e. including the (non-escaping) single quotes. This second call runs as desired.

How can I use a variable but still make the above call equivalent to the second code block written above?

1 Answers

You can easily see the effect of putting double quotes around the parameter with printf.

Here "first_word" and "second_word" are seeing as two parameters:

$ printf "%s\n" first_word second_word
first_word
second_word

While here as a single parameter:

$ printf "%s\n" "first_word second_word"
first_word second_word

This distinction holds true even if there's a variable expansion inside:

$ VAR="first_word second_word"
$ printf "%s\n" "${VAR}"
first_word second_word

More of this here:

[...] the double quotes protect the value of each parameter (variable) from undergoing word splitting or globbing should it happen to contain whitespace or wildcard characters

Related