I have a variable that I build like this :

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

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 ?

  • Where do the single quotes come from? – Oscar Aug 23 '12 at 11:55
  • 1
    Well, that's the problem. – drcelus Aug 23 '12 at 11:58
  • I tested this on my system, and both quoting the filename and quoting the entire string plus escape-quoting the filename work as advertised; since thi sis not reproducible it is due to some setting or translation happening on your side. – adaptr Aug 23 '12 at 12:11
  • I suspect this is IFS related. Try unsetting it. – Randy Proctor Mar 1 '13 at 15:32

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

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

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

# and for usage/display:

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

See the Bash Guide on Arrays for reference.

|improve this answer|||||
  • 1
    Thank you for the tip, but the same happens when I use an array, when expanded, single quotes appear. – drcelus Aug 23 '12 at 11:52
  • This is probably due to the quoting of the filename inside the assignment, then. – adaptr Aug 23 '12 at 12:04
  • @drcelus, in what context do single quotes appear? If it is in set -x output, don't worry about it: they appear just for your (visual) benefit, they don't affect the execution of the command. – glenn jackman Aug 23 '12 at 14:22
  • 1
    Somehow I missed @adaptr last edit on the answer (removed double quotations from the assignment), it now works like a charm. Thank you. – drcelus Aug 24 '12 at 6:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.