Xavier Silva Xavier Silva - 2 months ago 7
Linux Question

Bash - Executing a command in a script adding single quotes to a variable containing spaces

I am writing a script that executes all necessary commands to train a tesseract language and I want to receive a font as argument (e.g.: DejaVu Sans Bold) and execute this command

text2image --text=trainingFile.txt --outputbase=eng.DejaVuSansBold.exp0 --font='DejaVu Sans Bold' --fonts_dir=/usr/share/fonts
. Notice that
--font='DejaVu Sans Bold'
has the font name single quoted. Since I receive the font as an argument, I need to add the quotes and use the name.

After some different approaches, my "most effective" attempt was
text2image --text="${trainingTextFileName}" --outputbase="${languageCode}"."${fontNameWithoutBlanks}".exp0 --font="'""${fontName}""'" --fonts_dir=/usr/share/fonts
but it is still not working... ("languageCode" and "fontNameWithoutBlanks" are other variables).

After running the script with this line, I get a notification saying that the font is not recognized although it works perfectly when I execute it "manually" in the console.
set -x
set +x
the line (of the script) looks like this:
text2image --text=contentTraint.txt --outputbase=gdfdd.DejaVuSansBold.exp0 '--font='\''DejaVu Sans Bold'\''' --fonts_dir=/usr/share/fonts
. I have no idea how to go away from the extra quotation added because of the spaces...

Can anyone help me, please?


Be clear about the command you want to execute. When you type

text2image --text=trainingFile.txt --outputbase=eng.DejaVuSansBold.exp0 \
    --font='DejaVu Sans Bold' --fonts_dir=/usr/share/fonts

to the shell, what happens is that the shell invokes the command text2image with 4 arguments: --text=trainingFile.txt,
--font=DejaVu Sans Bold, --fonts_dir=/usr/share/fonts.

The purpose of the single quotes is just to tell the shell that --font=DejaVu Sans Bold is only one argument. In order to answer your question, though, we really need to know how you are executing the command (ie, you need to show some code). If you have the font name in the variable $font, you could do:

text2image --text=trainingFile.txt --outputbase=eng.DejaVuSansBold.exp0 \
    --font="$font" --fonts_dir=/usr/share/fonts

If the font is passed to your script as an argument, you could do:

text2image ... --font="$1" ...

If you are constructing the command more dynamically, you may need to do something else.