Shell – notify-send doesn’t work from script but works from terminal

command linenotificationsshell

I am trying to run this script:
test.sh

#!/bin/bash  
BAT_LEVEL=`acpi -b |grep -Eo "[0-9]+%"|grep -Eo "[0-9]+"`
CRIT=0                                                           
if [ $BAT_LEVEL -gt $CRIT ]; then
    echo "foo"
    aplay ~/apert.wav
    notify-send "Battery-Low"
    echo "bar"
fi  

The sixth line from above which is notify-send "Battery-Low" works just as you'd expect in terminal.
But when the script is executed it just spits out foo and bar on stdout.
I have no clue what the problem might be.

Best Answer

You are missing some environment variables, most likely the DISPLAY one. You could try the following:

echo "foo"                                                   
DISPLAY=:0.0 notify-send "Battery-Low"                                    
echo "bar"

If that doesn't help, you could compare the environment inside the script and in a terminal by running the env command in both.

Also note that if the script is being run as root, you may have to do something like this:

sudo -u yourUsername DISPLAY=:0.0 notify-send 'Battery low'
Related Question