1

This example is based on swaks, however it's not the only program I use where this problem is doing my head in :)

I have a variable SUBJECT="test subject"

and then I append commands to a string:

SWAKS="
     -t $TO
     -h-From $FROM
     --header Subject:$SUBJECT
     --body $BODY
     --auth
     --auth-user=user@domain.com
     --auth-password=d83kflb827Ms7d"

Then I'm executing it as ./swaks $SWAKS

but the subject of the message comes as test as everything after the space is ignored.

I tried changing the quotes into single ones, adding baslashes and nothing works. What am I doing wrong?

My latest try looked like this (output from stderr):

./swaks -t '$TO' '\' -h-From '"test' subject"'

this was using single qoutes at the start and end and double quotes around each variable.

Moseleyi
  • 2,585
  • 1
  • 24
  • 46
  • have you tried: SUBJECT="'test subject'" single quote inside the double quotes? – Eduardo G Mar 06 '17 at 14:25
  • 3
    As frequently is cited in case like this: http://mywiki.wooledge.org/BashFAQ/050 – Eric Renouf Mar 06 '17 at 14:30
  • Specifically, [section 1.5 of Bash FAQ 50](http://mywiki.wooledge.org/BashFAQ/050#I.27m_constructing_a_command_based_on_information_that_is_only_known_at_run_time). – chepner Mar 06 '17 at 15:06

2 Answers2

1

IMHO, keeping all command line arguments in a single variable is not a good idea. I'd rather make it like this:

./swaks                            \
    -t "$TO"                       \
    -h-From "$FROM"                \
    --header Subject:"$SUBJECT"    \
    --body "$BODY"                 \
    --auth                         \
    --auth-user=user@domain.com    \
    --auth-password=d83kflb827Ms7d
Oleg Andriyanov
  • 5,069
  • 1
  • 22
  • 36
  • The reason why I did it with one variable is because after that part of the command string there's a loop that adds attachments one by one. I couldn't figure out any other way to achieve both – Moseleyi Mar 06 '17 at 14:32
1

This is why bash provides arrays.

SWAKS=(
     -t "$TO"
     -h-From "$FROM"
     --header "Subject:$SUBJECT"
     --body "$BODY"
     --auth
     --auth-user=user@domain.com
     --auth-password=d83kflb827Ms7d
)

# Appending additional arguments to the array in a loop
for f in attachments/*; do
    # Same as SWAKS=( "${SWAKS[@]}" --attach "$f" )
    SWAKS+=( --attach "$f" )
done

./swaks "${SWAKS[@]}"
chepner
  • 497,756
  • 71
  • 530
  • 681