Bash Scripting – Problems with Variable Expansion Using Single Quotes

bashlinuxscripting

I have a variable that I build like this :

ATTSTR=""
for file in $LOCALDIR/*.pdf
do
  ATTSTR="${ATTSTR} -a \"${file}\""
done

The variable now contains (notice the whitespaces in the file name) :

ATTSTR=' -a "/tmp/Testpage - PDFCreator.pdf"'

And now I want to use this variable in a command like this one :

mutt -s "Subject" "${ATTSTR}" recipient@example.ec

But it turns out that it expands like this, and thus the command fails (notice the added single quotes surrounding the expanded variable):

mutt -s "Subject" ' -a "/tmp/Testpage - PDFCreator.pdf"' recipient@example.ec

I want my variable expanded without the single quotes, using "$ATTSTR" or $ATTSTR is just worse.
How can I achieve this ?

Best Answer

Filenames are notoriously unreliable in expanded strings; resist this temptation.

Instead, use an array to keep the filenames intact, regardless of any whitespace:

arr=()
for f in $somedir/*.pdf
do
arr+=( -a "$f")
done

# and for usage/display:

mutt -s mysubject "${a[@]}" some@body

See the Bash Guide on Arrays for reference.