Bash/sh helper function

This is an example of an sh function, which you can define in your sh scripts, to generate notifications using Notify17.

Note: to use this function, you need to create and copy a new raw API key, and replace the value of RAW_API_KEY.

Example
# This is the line you want to add to your scripts
# TODO copy/paste your raw API key
n17() { sh -c "$(wget -qO - "https://n17.io/sh")" -- -k "N17_RAW_API_KEY" "$@"; }

Here are some usage examples:

Example
#!/usr/bin/env sh

###
# Define the function.
###

# This is the line you want to add to your scripts
# TODO copy/paste your raw API key
n17() { sh -c "$(wget -qO - "https://n17.io/sh")" -- -k "N17_RAW_API_KEY" "$@"; }

###
# Below are some usage examples
###

# Simple title-only notification
n17 -t "Hello!"

# Notification with multiline content
n17 -t "Hello!" -c "This is a \nmultiline string"

# Process stdin
echo "I come from another command!" | n17 -t "Result" -c -

# Process stdin (title)
echo "I come from another command!" | n17 -t -

# Notification on success/error
command && n17 -t "Success!"
command || n17 -t "Failed!"

# Use the raw script to trigger a notification
sh -c "$(wget -qO - "https://n17.io/sh")" -- -k "N17_RAW_API_KEY" -t "Hello!"

The source code of this helper script can be found in its own GitHub repository  .

Bash: notify on execution error

The previous script can also be easily used to generate a notification automatically when a script fails.

To do so, you can leverage the power of Bash traps  , specifically the ERR trap, which invokes its function whenever an error is thrown.

Example

The following is an example on how to use a Bash ERR trap, to generate a notification on error.

In this example, when the thisCommandDoesNotExist command is invoked, Bash ERR trap will be triggered (n17TrapErr function), and the error notification will be generated.

Example
#!/bin/bash
# Halt execution on script error
set -e

# Define the n17 function to be used wherever you want to generate
# a notification
# TODO copy/paste your raw API key
n17() { sh -c "$(wget -qO - "https://n17.io/sh")" -- -k "N17_RAW_API_KEY" "$@"; }

# This function will be invoked on script error.
n17TrapErr() {
  n17 \
    -t "Script execution error!" \
    -c "$(cat <<CONTENT
Script ${BASH_SOURCE[0]} has encountered an error:

Exit code: $1
Line: $2
Command: $3

Trap arguments: $@
CONTENT
  )"
}

# Set up the error trap, which will forward all desired info for each error
trap 'n17TrapErr "$?" "$LINENO" "$BASH_COMMAND"' ERR

###
#
# Actual script execution
#
###

# Generate one notification to notify that the script has started
n17 -t "Script ${BASH_SOURCE[0]} started"

## This function will always throw an error
## (127, command not found)
thisCommandDoesNotExist

# We should not be able to get here
echo "Script finished successfully.. ???"