Sending Notifications from Bash Scripts
An automated script that fails quietly is barely better than no script. A backup that has not run for a week, a disk that filled up overnight, or a health check that reports CRITICAL into a log file nobody reads: each of these is only useful if a person finds out in time. Sending a notification, a message that reaches someone through email, a team chat or a phone, turns a script's result into an action.
Bash itself cannot send messages, but it can run the programs that do, mainly curl for web services. This lesson covers the common channels (email, chat webhooks, Telegram, push services and the system log), how to build the message payload correctly, how to keep the secret URLs secret, how to stop a slow or broken notification service from hurting the script, and how to notify once per problem instead of on every run. It ends with a reusable notify.sh that does all of this.
Choosing a Channel
| Channel | How a script sends | Typical use |
|---|---|---|
mail, sendmail, or cron's own mail of a job's output | reports, failures of scheduled jobs | |
| Slack, Discord, Microsoft Teams, Mattermost | an HTTP POST with a JSON body to an incoming webhook URL | team alerts |
| Telegram | an HTTP POST to the Bot API | personal or small-team alerts on a phone |
| ntfy, Gotify, Pushover | an HTTP POST with the message as the body | push notifications to a phone |
| System log | logger | a record that log collection and monitoring tools can pick up |
Email needs a working mail system on the server (a mail transfer agent, such as Postfix, configured to send through a mail relay). Many modern servers have none, and cron then simply discards job output (lesson 170). The web-based channels only need outbound HTTPS and curl, which is why they have become the usual choice for scripts.
When a mail system is configured, the mail command (from the mailutils or bsd-mailx packages) sends a message with a subject; the body comes from standard input:
mail -s "web01: backup failed" admin@example.com < /var/log/backup-last.log
sendmail -t reads a complete message, including its headers, from standard input, and is available wherever a mail transfer agent is installed:
sendmail -t <<EOF
To: admin@example.com
Subject: web01: backup failed
The nightly backup failed with status 2.
EOF
The test machine for this lesson had no mail system, so neither command was run there. For cron jobs, setting MAILTO and making the job print something only when it fails (lessons 170 and 172) is often all that is needed.
Chat webhooks
Slack, Discord, Microsoft Teams and similar services offer incoming webhooks: a channel administrator creates a webhook and receives a long, unguessable URL. Anything that sends an HTTP POST with the right JSON body to that URL posts a message to the channel. The body formats differ slightly:
| Service | Minimal JSON body | Message length limit |
|---|---|---|
| Slack | {"text": "..."} | about 40,000 characters |
| Discord | {"content": "..."} | 2,000 characters |
Telegram Bot API (sendMessage) | {"chat_id": "...", "text": "..."} | 4,096 characters |
The URL is the password. Anyone who has it can post to the channel, so it must be treated like any other secret (lesson 158): not written into a script that is shared or committed to Git, not shown in logs, and stored in a file only its owner can read.
Push services
ntfy (an open-source service, at ntfy.sh or self-hosted) is the simplest of all: the message is the plain-text body of a POST to a topic URL, and optional details such as the title and priority are HTTP headers:
curl -sS -H "Title: web01 backup" -H "Priority: high" -d "Backup failed" https://ntfy.sh/web01-alerts-x7f3k
Anyone who knows a public topic name can read and post to it, so on the public server the topic name works as a password too: it should be long and random.
The system log
logger writes a line to the system log, where journalctl and any log collection system can find it:
logger -t backup -p user.err 'backup of site failed'
-t sets the tag (the program name shown in the log) and -p the facility and priority. logger is a record, not an alert: nobody is told. It is also not a reliable test that the record arrived: on the test machine, which had no system log service (/dev/log did not exist), the command above returned status 0 and the message went nowhere.
Building the Message Body Safely
The most common mistake in notification scripts is building JSON by pasting a variable into a string. Messages from scripts often contain exactly the characters JSON treats specially: double quotes in file names, backslashes in Windows paths, and newlines in multi-line output. A test webhook receiver on the test machine printed every request it received and checked whether the JSON was valid:
webhook=http://127.0.0.1:8099/services/T0/B0/secret
msg=$'Backup of "site" failed\nDisk full on /srv'
curl -sS -H 'Content-Type: application/json' -d "{\"text\": \"$msg\"}" "$webhook"
invalid_payload
The receiver logged what it got:
POST /services/T0/B0/secret type=application/json
body: {"text": "Backup of "site" failed\nDisk full on /srv"}
(INVALID JSON: Expecting ',' delimiter: line 1 column 22 (char 21))
The quote before site ended the JSON string early. (The real newline in the message is not allowed inside a JSON string either; the receiver shows it as \n.) Real services answer such a request with an error, and the alert is lost exactly when it matters.
jq (lesson 156) builds JSON correctly from any text. --arg NAME VALUE passes a value into jq as a string variable, and jq escapes it when it writes the result:
payload=$(jq -n --arg text "$msg" '{text: $text}')
echo "$payload"
curl -sS -H 'Content-Type: application/json' -d "$payload" "$webhook"
jq -nc --arg text "$msg" '{text: $text}'
{
"text": "Backup of \"site\" failed\nDisk full on /srv"
}
ok
{"text":"Backup of \"site\" failed\nDisk full on /srv"}
-n tells jq not to read any input, and -c produces compact, single-line output. The quotes became \" and the newline became \n, as JSON requires, and the receiver accepted the payload.
A message starting with @
curl's -d and --data-binary options treat a value that starts with @ as a file name and send that file's contents. A message that happens to start with @, such as one built from user input, could therefore send a local file to an outside service:
curl -sS -d '@/etc/hostname' http://127.0.0.1:8099/at-test-d
curl -sS --data-binary '@/etc/hostname' http://127.0.0.1:8099/at-test-binary
POST /at-test-d type=application/x-www-form-urlencoded
body: vm
POST /at-test-binary type=application/x-www-form-urlencoded
body: vm\n
Both requests sent the contents of /etc/hostname (vm) instead of the text @/etc/hostname. (-d also removes newlines from the file, while --data-binary sends it unchanged.) The safe form is --data-binary @-, which reads the body from standard input, so the message is never interpreted, or --data-raw, which never treats @ specially.
Keeping the URL Out of the Process List
On Linux, every user can see the full command line of every process, for example with ps. A webhook URL passed to curl as an argument is visible for as long as the request runs. A slow request on the test machine showed it:
$ ps -o args= -C curl
curl -sS --max-time 5 -d x http://127.0.0.1:8099/slow/T0/B0/slack-secret
curl can read options from a configuration file with -K FILE, where each line has the form option = "value". The file can be a here-string on a spare file descriptor, so the URL never appears as an argument and never touches the disk:
curl -sS --max-time 5 -d x -K /dev/fd/3 3<<< 'url = "http://127.0.0.1:8099/slow/T0/B0/slack-secret"'
$ ps -o args= -C curl
curl -sS --max-time 5 -d x -K /dev/fd/3
3<<< connects a here-string to file descriptor 3 of curl, and /dev/fd/3 is the path curl opens to read it. Standard input stays free for the message body. Since Bash 5.1, a short here-string is passed through a pipe rather than a temporary file, so the URL is not written to disk either. Because the value is inside double quotes in curl's configuration syntax, a URL containing a double quote or a backslash would break it; real webhook URLs never contain either, and the script below rejects such URLs.
Failures, Timeouts and Retries
A notification is a side task. A failing chat service must not make a backup script fail, and a hanging one must not make it hang. Three curl options control this:
--max-time SECONDSlimits each attempt (lesson 168).--fail-with-bodymakes curl exit with status 22 when the server answers with an HTTP error (400 and above), instead of the default 0. Without it, a rejected message counts as a success.--retry Nrepeats a failed attempt up to N times, waiting 1, then 2, then 4 seconds and so on. curl retries only transient errors: timeouts and the HTTP statuses 408, 429, 500, 502, 503 and 504. A refused connection is retried only with--retry-connrefused.--retry-max-timecaps the total time spent retrying.
Retries and -o /dev/null
The usual way to discard the server's answer is -o /dev/null. Together with --retry, it breaks retrying: before a retry, curl tries to empty the output file, which fails for /dev/null, and curl gives up with status 23 ("write error"). The test receiver had an endpoint that answered 503 twice and then 200:
curl -sS --fail-with-body --retry 2 -o /dev/null --data-binary 'hello' http://127.0.0.1:8099/flaky/a; echo "status $?"
curl -sS --fail-with-body --retry 2 --data-binary 'hello' http://127.0.0.1:8099/flaky/e > /dev/null; echo "status $?"
curl: (22) The requested URL returned error: 503
status 23
curl: (22) The requested URL returned error: 503
curl: (22) The requested URL returned error: 503
status 0
The receiver confirmed one attempt for the first command and three for the second:
POST /flaky/a -> 503 (attempt 1)
POST /flaky/e -> 503 (attempt 1)
POST /flaky/e -> 503 (attempt 2)
POST /flaky/e type=application/x-www-form-urlencoded
body: hello
When the shell redirects curl's standard output to /dev/null, curl does not try to empty it, and the retries work. Each failed attempt prints its own error line.
A timeout does not mean "not delivered"
A timeout only means that no answer arrived in time. The test receiver had a path that waited 20 seconds before answering. With --max-time 10 --retry 2 --retry-max-time 30, notify.sh (below) gave up after 33 seconds, but the receiver had logged the message on each attempt: the service received it, and only the answer was late. Retries on timeouts can therefore produce duplicate messages. For alerts, a duplicate is a much smaller problem than a lost alert, but it is the reason to keep time limits generous and the number of retries small.
Notify Once per Problem
A health check that runs every five minutes (lesson 172) and sends an alert on every run produces 288 identical messages a day for a problem that nobody can fix until morning. People quickly start ignoring the channel, and then they also miss the next new problem. A better rule is to notify when the situation changes:
- a new problem, or a different set of problems: send;
- the same problem as last time: stay quiet;
- no problem after a problem: send one "resolved" message.
A script can implement this by remembering what it last sent. It does not need to store the whole message; a checksum of it (a short fixed-length fingerprint, here from sha256sum) is enough to tell whether the new message is the same. The script below keeps one small file per key, the name of the thing being watched, such as health or backup-site.
Two details matter. First, the state is updated only after every channel accepted the message, so a notification that failed is tried again on the next run instead of being marked as sent. Second, the comparison is on the exact text: if the message contains a value that changes every run, such as "7474 MiB available", every run looks like a change. Messages used with this technique should contain stable text, such as the status and the name of the failing check.
A Complete Example: notify.sh
notify.sh sends a message to every channel listed in a configuration file, with an optional title and optional change detection:
#!/usr/bin/env bash
#
# notify.sh - send a message to the chat and push services listed in a config file
#
# Usage: notify.sh [-c CONFIG] [-t TITLE] [-k KEY] MESSAGE
# notify.sh [-c CONFIG] [-t TITLE] [-k KEY] - (message from standard input)
# -c CONFIG channel list (default: /etc/notify.conf, must not be readable by others)
# -t TITLE short title, e.g. the host and job name (default: the host name)
# -k KEY only notify when the message for KEY changes; an empty message
# after a non-empty one sends a "resolved" notice
#
# Config lines (blank lines and lines starting with # are ignored):
# slack WEBHOOK_URL
# discord WEBHOOK_URL
# ntfy TOPIC_URL
# telegram https://api.telegram.org/botTOKEN/sendMessage CHAT_ID
#
# Exit status: 0 sent to every channel (or nothing to send), 1 at least one
# channel failed, 2 usage or configuration error
set -uo pipefail
export LC_ALL=C.UTF-8 # ${var:0:N} then counts characters, not bytes
config=/etc/notify.conf
title=$(hostname)
key=''
state_dir=${NOTIFY_STATE_DIR:-/var/lib/notify}
usage() { echo "usage: ${0##*/} [-c CONFIG] [-t TITLE] [-k KEY] MESSAGE|-" >&2; exit 2; }
err() { echo "${0##*/}: $*" >&2; }
while getopts ':c:t:k:' opt; do
case $opt in
c) config=$OPTARG ;;
t) title=$OPTARG ;;
k) [[ $OPTARG =~ ^[A-Za-z0-9._-]+$ ]] || { err "invalid key '$OPTARG'"; exit 2; }
key=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 1 )) || usage
if [[ $1 == - ]]; then
message=$(cat)
else
message=$1
fi
# The webhook URLs are passwords: anyone who has one can post to the channel.
[[ -f $config && -r $config ]] || { err "cannot read config file '$config'"; exit 2; }
mode=$(stat -c %a -- "$config")
if (( 8#$mode & 8#077 )); then
err "config file '$config' has mode $mode; it must not be accessible by others (chmod 600)"
exit 2
fi
# --- send only on change (-k) ------------------------------------------------
state_file='' resolved=0
if [[ -n $key ]]; then
mkdir -p -- "$state_dir" || exit 2
state_file=$state_dir/$key.sha256
new_sum=''
[[ -n $message ]] && new_sum=$(printf '%s' "$message" | sha256sum | cut -d' ' -f1)
old_sum=$(cat -- "$state_file" 2>/dev/null)
if [[ $new_sum == "$old_sum" ]]; then
exit 0 # nothing new to report
fi
if [[ -z $message ]]; then
message="RESOLVED: the problem reported earlier is gone."
resolved=1
fi
fi
[[ -n $message ]] || exit 0 # nothing to send
# --- sending -----------------------------------------------------------------
# post URL CONTENT_TYPE BODY [HEADER...]
# The URL reaches curl as a config file on descriptor 3 (-K), so it never
# appears in the process list, where other users could read it. The body
# comes from standard input (@-), so a message starting with @ is not taken
# as a file name. The server's answer goes to /dev/null through the shell, not
# with -o /dev/null, which makes curl fail with status 23 when it retries; curl's
# error messages (one per attempt) go to standard output for the caller.
post() {
local url=$1 type=$2 body=$3; shift 3
local args=( -sS --fail-with-body --max-time 10 --retry 2 --retry-max-time 30
-H "Content-Type: $type" --data-binary @- )
local header
for header in "$@"; do args+=( -H "$header" ); done
curl "${args[@]}" -K /dev/fd/3 3<<< "url = \"$url\"" < <(printf '%s' "$body") 2>&1 > /dev/null
}
send() {
local type=$1 url=$2 extra=${3-} text="$title: $message" body
[[ $url == https://* || $url == http://* ]] || { echo "not an http(s) URL"; return 1; }
[[ $url != *[\"\\]* ]] || { echo "URL contains a quote or backslash"; return 1; }
case $type in
slack) body=$(jq -nc --arg t "$text" '{text: $t}')
post "$url" application/json "$body" ;;
discord) body=$(jq -nc --arg t "${text:0:2000}" '{content: $t}')
post "$url" application/json "$body" ;;
telegram) [[ -n $extra ]] || { echo "chat id missing"; return 1; }
body=$(jq -nc --arg c "$extra" --arg t "${text:0:4096}" '{chat_id: $c, text: $t}')
post "$url" application/json "$body" ;;
ntfy) # ntfy takes the message as plain text and the title as a header;
# header values must be a single line.
post "$url" 'text/plain; charset=utf-8' "$message" \
"Title: ${title//[$'\r\n']/ }" ;;
*) echo "unknown channel type"; return 1 ;;
esac
}
failed=0 sent=0 line_no=0
while read -r type url extra rest || [[ -n ${type:-} ]]; do
(( line_no++ ))
[[ -z ${type:-} || $type == \#* ]] && continue
if [[ -z ${url:-} || -n ${rest:-} ]]; then
err "$config line $line_no: expected TYPE URL [CHAT_ID]"
failed=1
continue
fi
if result=$(send "$type" "$url" "${extra:-}"); then
(( sent++ ))
else
# Report the channel type and line, never the URL itself; after
# retries, the last line holds curl's final error.
result=${result##*$'\n'}
err "$type channel (line $line_no) failed: ${result:-no details}"
failed=1
fi
done < "$config"
if (( sent == 0 && failed == 0 )); then
err "no channels configured in '$config'"
exit 2
fi
# Remember what was reported only when every channel got it, so that a
# failed notification is tried again on the next run.
if [[ -n $state_file ]] && (( failed == 0 )); then
if (( resolved )); then
rm -f -- "$state_file"
else
printf '%s\n' "$new_sum" > "$state_file"
fi
fi
exit "$failed"
How It Works
- The message comes from the argument, or from standard input when the argument is
-, so another script's output can be piped in. - The configuration file has one channel per line: a type and a URL, plus a chat ID for Telegram. Because the URLs are secrets, the script refuses to use a file that anyone except its owner can read or write.
stat -c %agives the permission bits as an octal number such as600,8#$modereads that number as octal in Bash arithmetic, and& 8#077keeps only the group and other bits, which must be zero. - Change detection with
-k KEY. The checksum of the last message sent for that key is kept in$NOTIFY_STATE_DIR/KEY.sha256(by default under/var/lib/notify). The same message as last time ends the script quietly; an empty message after a non-empty one turns into a "resolved" notice, and theresolvedflag makes the script delete the state file afterwards. The key is restricted to safe characters because it becomes part of a file name. - One
sendper channel type builds the body in that service's format withjq -nc --arg, and shortens the text to the service's length limit with${text:0:N}. UnderLC_ALL=C.UTF-8, that expansion counts characters, so a cut never splits a multi-byte character. ntfy gets the plain message as the body and the title as a header; any newline in the title is replaced with a space, because a header must be a single line. postruns curl with a 10-second limit per attempt, two retries within at most 30 seconds, and--fail-with-body. The URL arrives as a curl configuration on descriptor 3, the body on standard input. The order2>&1 > /dev/nullfirst points curl's error output at the function's standard output, where the caller captures it, and then discards the server's answer (lesson 60).- Error reports never contain the URL. A failed channel is reported by type and line number, with the last line of curl's error messages. The other channels are still tried.
- Exit status. 0 when every channel accepted the message or there was nothing new to send, 1 when at least one channel failed, and 2 for usage and configuration errors. A calling script can decide whether a failed notification matters; most should not stop because of one.
Running the Complete Example
The test receiver (a small Python web server on port 8099) printed each request it received. The configuration file listed four channels, with local URLs standing in for the real services, and was made readable only by its owner:
# where alerts go
slack http://127.0.0.1:8099/services/T0/B0/slack-secret
discord http://127.0.0.1:8099/api/webhooks/123/discord-secret
ntfy http://127.0.0.1:8099/web01-alerts-x7f3k
telegram http://127.0.0.1:8099/bot123:telegram-secret/sendMessage -1001234567
chmod 600 notify.conf
notify.sh -c notify.conf -t 'web01 backup' $'Backup of "site" failed\nexit status 2, see /var/log/backup.log'
The command printed nothing and exited with 0. Each service received the message in its own format, with the quotes and the newline correctly encoded:
POST /services/T0/B0/slack-secret type=application/json
body: {"text":"web01 backup: Backup of \"site\" failed\nexit status 2, see /var/log/backup.log"}
(valid JSON)
POST /api/webhooks/123/discord-secret type=application/json
body: {"content":"web01 backup: Backup of \"site\" failed\nexit status 2, see /var/log/backup.log"}
(valid JSON)
POST /web01-alerts-x7f3k type=text/plain; charset=utf-8 {'Title': 'web01 backup'}
body: Backup of "site" failed\nexit status 2, see /var/log/backup.log
POST /bot123:telegram-secret/sendMessage type=application/json
body: {"chat_id":"-1001234567","text":"web01 backup: Backup of \"site\" failed\nexit status 2, see /var/log/backup.log"}
(valid JSON)
A message beginning with @ is sent as text, because the body goes through standard input:
$ notify.sh -c one.conf -t web01 '@/etc/hostname'
[status 0]
POST /web01-alerts-x7f3k type=text/plain; charset=utf-8 {'Title': 'web01'}
body: @/etc/hostname
Change detection
one.conf contains only the ntfy channel. Five calls with the key health: a problem, the same problem, a second problem added, an empty message, and another empty message:
$ notify.sh -c one.conf -t web01 -k health 'CRITICAL process cron: not running'
[status 0]
$ notify.sh -c one.conf -t web01 -k health 'CRITICAL process cron: not running'
[status 0]
$ notify.sh -c one.conf -t web01 -k health $'CRITICAL process cron: not running\nWARNING disk /: 85% used'
[status 0]
$ notify.sh -c one.conf -t web01 -k health ''
[status 0]
$ notify.sh -c one.conf -t web01 -k health ''
[status 0]
Only three messages arrived: the first problem, the changed situation, and the recovery:
POST /web01-alerts-x7f3k type=text/plain; charset=utf-8 {'Title': 'web01'}
body: CRITICAL process cron: not running
POST /web01-alerts-x7f3k type=text/plain; charset=utf-8 {'Title': 'web01'}
body: CRITICAL process cron: not running\nWARNING disk /: 85% used
POST /web01-alerts-x7f3k type=text/plain; charset=utf-8 {'Title': 'web01'}
body: RESOLVED: the problem reported earlier is gone.
Combined with the health check
The quiet mode of healthcheck.sh from lesson 172 prints only problems, which is exactly the input -k expects. The same pipeline was run four times, twice with a configuration that has two problems and twice with the healthy configuration:
healthcheck.sh -q -c two.conf | notify.sh -c one.conf -t 'web01 health' -k health -
All four runs printed nothing and exited with 0, and two messages arrived:
POST /web01-alerts-x7f3k type=text/plain; charset=utf-8 {'Title': 'web01 health'}
body: WARNING disk /: 29% used (warn 20%, crit 90%)\nCRITICAL process cron: not running\n-- CRITICAL: 0 OK, 1 WARNING, 1 CRITICAL, 0 UNKNOWN
POST /web01-alerts-x7f3k type=text/plain; charset=utf-8 {'Title': 'web01 health'}
body: RESOLVED: the problem reported earlier is gone.
As a crontab entry, this checks every five minutes but only notifies when something changes:
*/5 * * * * /usr/local/bin/healthcheck.sh -q -c /etc/healthcheck.conf | /usr/local/bin/notify.sh -t "web01 health" -k health -
Failures
fail.conf contains a Slack URL that always answers 500, a Discord URL that answers 503 twice before accepting, an ntfy URL on a port where nothing listens, and a Telegram line without a chat ID:
$ notify.sh -c fail.conf -t web01 -k disk 'WARNING disk /: 85% used'
notify.sh: slack channel (line 1) failed: curl: (22) The requested URL returned error: 500
notify.sh: ntfy channel (line 3) failed: curl: (7) Failed to connect to 127.0.0.1 port 9 after 0 ms: Couldn't connect to server
notify.sh: telegram channel (line 4) failed: chat id missing
[status 1]
The run took 6 seconds. The receiver shows the retries: Slack was tried three times and failed each time; Discord succeeded on the third attempt, so it does not appear in the errors. The refused connection was not retried. No URL appears in the error messages, and no state file was written, so the next run with the same message tries again.
POST /down/T0/B0/slack-secret -> 500
POST /down/T0/B0/slack-secret -> 500
POST /down/T0/B0/slack-secret -> 500
POST /flaky/123/discord-secret -> 503 (attempt 1)
POST /flaky/123/discord-secret -> 503 (attempt 2)
POST /flaky/123/discord-secret type=application/json
body: {"content":"web01: WARNING disk /: 85% used"}
(valid JSON)
A service that does not answer at all costs at most about half a minute, then the script gives up:
$ notify.sh -c slow.conf -t web01 'test'
notify.sh: ntfy channel (line 1) failed: curl: (28) Operation timed out after 10003 milliseconds with 0 bytes received
[status 1]
That run took 33 seconds: three attempts of 10 seconds each, plus the waits of 1 and 2 seconds between them.
Configuration and usage errors
$ chmod 644 notify.conf; notify.sh -c notify.conf 'test'
notify.sh: config file 'notify.conf' has mode 644; it must not be accessible by others (chmod 600)
[status 2]
$ notify.sh -c nope.conf 'test'
notify.sh: cannot read config file 'nope.conf'
[status 2]
$ notify.sh -c notify.conf
usage: notify.sh [-c CONFIG] [-t TITLE] [-k KEY] MESSAGE|-
[status 2]
$ notify.sh -c notify.conf -k 'bad key' x
notify.sh: invalid key 'bad key'
[status 2]
$ notify.sh -c empty.conf hi
notify.sh: no channels configured in 'empty.conf'
[status 2]
Using It from Other Scripts
Because failures are reported on standard error and through the exit status, a script can send a notification without letting a notification problem change its own result:
if ! /usr/local/bin/backup.sh; then
/usr/local/bin/notify.sh -t "$(hostname) backup" "Nightly backup failed, see /var/log/backup.log" ||
logger -t backup -p user.err "backup failed and the notification could not be sent"
fi
Combined with an ERR or EXIT trap (lesson 123), the same call can report any unexpected failure of a longer script.