Shell embed variable with spaces inside the string

2019-07-24 05:37发布

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.

标签: bash shell
2条回答
甜甜的少女心
2楼-- · 2019-07-24 06:03

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
查看更多
祖国的老花朵
3楼-- · 2019-07-24 06:11

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[@]}"
查看更多
登录 后发表回答