Home > Enterprise >  bash vs sh: script works in sh but not in bash
bash vs sh: script works in sh but not in bash

Time:07-04

I know that bash is the default shell on macOS and that bash is backward compatible with sh. My script, however, completes successfully in sh but breaks in bash. Any idea why?

echo "From: Adam @ Pinfluence Media <[email protected]>\nTo: $2\nSubject: Pin Images Ready\nMime-Version: 1.0\nContent-Type: text/html\n\n<html><body><p>Hello $1,</p><p>Your pin images are ready at the link below. We will pass them on to the manager as well.</p><p>$3</p><p>Best Regards,</p><p>Adam @ <a href='https://pinfluencemedia.com'>Pinfluence Media</a></p></body></html>" > mail.msg

mailutils send -T $2 smtps://adam\@pinfluencemedia.com:0***********[email protected] mail.msg

rm mail.msg

The error I get in bash only is:

send.c:164: mu_mailer_send_message (mailer, msg, from_addr, rcpt_addr) failed: Operation rejected by remote party
images-inform.sh: line 19: 14868 Abort trap: 6           mailutils send -T $2 smtps://adam\@pinfluencemedia.com:0***********[email protected] mail.msg

Line 19 is the mailutils … line.

Thanks for any help.

CodePudding user response:

In bash you need to specify the -e option if you want echo to translate your \n to literal newlines. For example echo -e 'a\nb'
But with a generic sh, echo - most probably - won't support the -e option; and what POSIX states about \n is:

if any of the operands contain a backslash ( \ ) character, the results are implementation-defined.

That means that you can't know what will happen with your \n; some echo implementations will translate it, while others won't...

The way to work around the unpredictability of echo is to avoid it and use printf instead:

printf '%s\n' \
    "From: Adam @ Pinfluence Media <[email protected]>" \
    "To: $2" "Subject: Pin Images Ready" "Mime-Version: 1.0" \
    "Content-Type: text/html" \
    "" \
    "<html><body><p>Hello $1,</p><p>Your pin images are ready at the link below. We will pass them on to the manager as well.</p><p>$3</p><p>Best Regards,</p><p>Adam @ <a href='https://pinfluencemedia.com'>Pinfluence Media</a></p></body></html>" \
    > mail.msg

# or

printf %s "\
From: Adam @ Pinfluence Media <[email protected]>
To: $2
Subject: Pin Images Ready
Mime-Version: 1.0
Content-Type: text/html

<html><body><p>Hello $1,</p><p>Your pin images are ready at the link below. We will pass them on to the manager as well.</p><p>$3</p><p>Best Regards,</p><p>Adam @ <a href='https://pinfluencemedia.com'>Pinfluence Media</a></p></body></html>
" > mail.msg
  • Related