4

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}" [email protected]

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"' [email protected]

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

4
  • Where do the single quotes come from?
    – Oscar
    Aug 23, 2012 at 11:55
  • 1
    Well, that's the problem.
    – drcelus
    Aug 23, 2012 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, 2012 at 12:11
  • I suspect this is IFS related. Try unsetting it. Mar 1, 2013 at 15:32

2 Answers 2

7

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.

4
  • 1
    Thank you for the tip, but the same happens when I use an array, when expanded, single quotes appear.
    – drcelus
    Aug 23, 2012 at 11:52
  • This is probably due to the quoting of the filename inside the assignment, then.
    – adaptr
    Aug 23, 2012 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. Aug 23, 2012 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, 2012 at 6:11
1

Use eval function

command="mutt -s \"Subject\" $ATTSTR [email protected]"
response=$(eval "$command")

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .