2026-07-15

Sending email using unix shell scripting

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Sending email using unix shell scripting

Mastering Shell Scripting: Sending Emails with Variables in Bash

As developers, we often find ourselves needing to automate tedious tasks, and command-line scripting, particularly using Unix shell scripts (like Bash), is a powerful tool for system administration and automation. One common task is sending notifications or reports via email. However, handling dynamic content—like variable subject lines or message bodies—correctly within the script can often lead to subtle errors.

This post dives into a specific challenge: how to correctly incorporate shell variables into command-line utilities like the mail command when sending emails. We will analyze an example and provide robust solutions based on best practices.

The Challenge: Variables in Shell Commands

The initial attempt provided highlights a common pitfall when mixing standard shell variable expansion ($variable) with external command arguments (like those used by mail).

Here is the problematic scenario:

#!/bin/bash
# Sending mail to remote user

sender="root@sped56.lss.emc.com"
receiver="root@sped56.lss.emc.com"
body="THIS IS THE BODY"
subj="THIS IS THE SUBJECT."

# Attempt 1: Works fine (using quotes around the entire string)
echo $body | mail $receiver -s "THIS IS THE SUBJECT"

# Attempt 2: Fails (shell expands the command arguments before 'mail' sees them fully)
echo $body | mail $receiver -s $subj

The reason the second attempt fails is due to how the shell interprets the command line. When you use $subj directly, the shell attempts to substitute the variable before passing the argument to the mail command. If the variable contains spaces or special characters, or if quoting rules are misapplied, the resulting arguments passed to mail -s become corrupted, leading to unintended behavior like sending multiple emails or truncation errors.

The Solution: Prioritizing Quoting and Command Substitution

The key to reliably passing shell variables to external commands is meticulous use of quotation marks. When dealing with piping (|), it is generally safer to ensure that the entire command being executed is treated as a single unit, or to use proper command substitution if complex logic is involved.

Method 1: Correct Quoting for Simple Arguments

For simple arguments passed directly to flags like -s, enclosing the variable in double quotes ensures that the shell treats the entire content as a single argument, preventing word splitting and misinterpretation.

#!/bin/bash
sender="root@sped56.lss.emc.com"
receiver="root@sped56.lss.emc.com"
body="THIS IS THE BODY"
subj="THIS IS THE SUBJECT."

# Correct implementation: Use quotes around the variable expansion
echo "$body" | mail $receiver -s "$subj"

By wrapping $subj in double quotes ("$subj"), we ensure that if the subject contained spaces, it would be passed to the mail command as a single, properly quoted argument. This approach is fundamental to writing robust automation scripts, whether you are managing infrastructure or developing backend logic, much like ensuring data integrity in a Laravel application.

Method 2: Using Heredocs for Complex Messages (Best Practice)

For sending multi-line messages, using echo piped into mail is fine, but for cleaner separation of message body and subject, Heredocs (<<EOF) offer superior readability and control over the content structure. This method is highly recommended when building complex notifications.

#!/bin/bash
sender="root@sped56.lss.emc.com"
receiver="root@sped56.lss.emc.com"
subj="Automated Report for Today"
message_body=$(cat <<EOF
Dear Administrator,

Please find the automated report attached below.
Date: $(date)
---------------------
$body
EOF
)

# Send the constructed message
echo "$message_body" | mail -s "$subj" "$receiver"

In this example, we first construct the entire body dynamically using a Here Document, and then pass that complete string to the mail command along with the subject. This approach separates the logic for content generation from the execution of the sending command, making the script far more maintainable.

Conclusion

Sending emails via shell scripting is entirely achievable, but it requires a deep understanding of how the shell parses commands and handles variable expansion. The lesson learned here is that quoting is not optional; it is mandatory for reliable automation. Always treat variables as potential inputs that require strict encapsulation when interacting with external programs. By adopting these quoting and structuring techniques, you can write scripts that are not only functional but also robust, scalable, and easy to debug, enhancing your overall development workflow significantly.

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.