Skip to content

Commit 6af8d03

Browse files
committed
Add Terminal Notifications for Long-Running Commands example
Signed-off-by: Sharjeel Aziz <sharjeel.aziz@gmail.com>
1 parent 630f295 commit 6af8d03

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

docs/examples.md

+59
Original file line numberDiff line numberDiff line change
@@ -634,3 +634,62 @@ or by simply providing traccar with a valid username/password combination.
634634
<entry key='sms.http.user'>phil</entry>
635635
<entry key='sms.http.password'>mypass</entry>
636636
```
637+
638+
## Terminal Notifications for Long-Running Commands
639+
640+
This example provides a simple way to send notifications using [ntfy.sh](https://ntfy.sh) when a terminal command completes. It includes success or failure indicators based on the command's exit status.
641+
642+
### Setup
643+
644+
1. Store your ntfy.sh bearer token securely if access control is enabled:
645+
646+
```sh
647+
echo "your_bearer_token_here" > ~/.ntfy_token
648+
chmod 600 ~/.ntfy_token
649+
```
650+
651+
1. Add the following function and alias to your `.bashrc` or `.bash_profile`:
652+
653+
```sh
654+
# Function for alert notifications using ntfy.sh
655+
notify_via_ntfy() {
656+
local exit_status=$? # Capture the exit status before doing anything else
657+
local token=$(< ~/.ntfy_token) # Securely read the token
658+
local status_icon="$([ $exit_status -eq 0 ] && echo magic_wand || echo warning)"
659+
local last_command=$(history | tail -n1 | sed -e 's/^[[:space:]]*[0-9]\{1,\}[[:space:]]*//' -e 's/[;&|][[:space:]]*alert$//')
660+
661+
curl -s -X POST "https://n.example.dev/alerts" \
662+
-H "Authorization: Bearer $token" \
663+
-H "Title: Terminal" \
664+
-H "X-Priority: 3" \
665+
-H "Tags: $status_icon" \
666+
-d "Command: $last_command (Exit: $exit_status)"
667+
668+
echo "Tags: $status_icon"
669+
echo "$last_command (Exit: $exit_status)"
670+
}
671+
672+
# Add an "alert" alias for long running commands using ntfy.sh
673+
alias alert='notify_via_ntfy'
674+
675+
```
676+
677+
### Usage
678+
679+
Run any long-running command and append `alert` to notify when it completes:
680+
681+
```sh
682+
sleep 10; alert
683+
```
684+
![ntfy notifications on mobile device](static/img/mobile-screenshot-notification.png)
685+
686+
**Notification Sent** with a success 🪄 (`magic_wand`) or failure ⚠️ (`warning`) tag.
687+
688+
#### Simulating Failures
689+
690+
To test failure notifications:
691+
692+
```sh
693+
false; alert # Always fails (exit 1)
694+
ls --invalid; alert # Invalid option
695+
cat nonexistent_file; alert # File not found
Loading

0 commit comments

Comments
 (0)