I am trying to create a tiny application on my Ubuntu machine. What I want to do is put to an icon on my taskbar beside the volume, and internet connectivity options. I understand that there is a notify-send
command in bash that I can use, or even switch to Qt
but that seems to be an overkill for the problem. Concretely, is there a way to create an icon on Ubuntu taskbar with bash, and change its color or text periodically?
For a very shell friendly way to quickly get tray apps working use yad (specifically yad --notification
). It allows you to dynamically change icons, set click event handlers and build a custom context menu. For example:
yad --notification --command='echo hello world' --image=myicon.png
Will echo 'hello world' on click. Or:
yad --notification --command='echo hello world' --image=myicon.png --listen
Will read it's standard input waiting for commands to change icons, change visibility, open menu, trigger action and more.
More advanced example using yad.
Shows how to handle click in the same script and how to change the icon on the click. Also shows how to create a simple update loop and exit cleanly.
# stop on error (always good practice)
set -e
# create a FIFO file, used to manage the I/O redirection from shell
PIPE=$(mktemp -u --tmpdir ${0##*/}.XXXXXXXX)
mkfifo $PIPE
export PIPE
# attach a file descriptor to the file
exec 3<> $PIPE
# add handler to manage process shutdown
function on_exit() {
# send command to yad through pipe
echo "quit" >&3
rm -f $PIPE
}
trap on_exit EXIT
function update_icon() {
exec 3<> $PIPE # just in case
echo "icon:/path/to/some/icon" >&3
}
export -f update_icon
# add handler for tray icon left click
function on_click() {
exec 3<> $PIPE # required
echo "clicked"
echo "icon:/path/to/icon" >&3
update_icon
}
export -f on_click
# add handler for right click menu Quit entry function
on_quit() {
# signal to the script that it should end when this file is created
echo "quit" > ./quit.txt
exec 3<> $PIPE # required
echo "quit" >&3
}
export -f on_quit
# Use a file to indicate a quit command to the script
# Make sure it is gone before we start the program to avoid immediate exit
rm -f quit.txt
# create the notification icon with right click menu and Quit option
yad --notification \
--listen \
--image="/path/to/icon" \
--text="demo tray icon" \
--menu="Quit!bash -c on_quit" \
--no-middle \
--command="bash -c on_click" <&3 &
# allow user to end the loop from icon right click Quit menu option
while [ ! -f "quit.txt" ]; do
#echo "Press [CTRL+C] to stop.."
update_icon
sleep 60
done
# clean up after quit
rm quit.txt
Based on:
I'm not a bash expert, so fixes are welcome.
yad
is available for many distros as a standard package. On Debian for example it can be installed by apt install yad
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With