Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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 ?

share|improve this question
    
Where do the single quotes come from? –  Oscar Aug 23 '12 at 11:55
    
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

2 Answers 2

up vote 5 down vote accepted

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.

share|improve this answer
    
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

I suspect this is IFS related. Try unsetting it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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