Search code examples
linuxbashbattery

Turn off PC and do something before with BASH


I want to turn off the PC and copy some files before the battery is empty.

#!/bin/bash
LOW=11460
BAT=`/bin/cat /proc/acpi/battery/BAT1/state | /bin/grep remaining | /usr/bin/awk '{print\$3}'`
if ["$BAT" \< "$LOW"]
then
echo "Turning off"
rsync folder/ otherfolder/
shutdown -h now
fi

But its doesn't work!


Solution

  • Your syntax is incorrect. You are unnecessarily escaping parts of your code and your test expression needs spaces surrounding the variables and a numeric comparison when using the [ construct. e.g.:

    #!/bin/bash
    LOW=11460
    BAT=`/bin/cat /proc/acpi/battery/BAT1/state | /bin/grep remaining | /usr/bin/awk '{print $3}'`
    if [ "$BAT" -lt "$LOW" ]
    then
        echo "Turning off"
        rsync folder/ otherfolder/
        shutdown -h now
    fi
    

    Presuming both /bin and /usr/bin are in your path, I would make the following changes:

    BAT=`cat /proc/acpi/battery/BAT1/state | grep remaining | awk '{print $3}'`
    

    Consider also using (()) as your test expression. e.g.

    if ((BAT < LOW))
    

    Note: spaces surrounding BAT and LOW are not required when using the (()) test construct, and there is no need to dereference your variable with $ inside (()) unless using brace expansion or array syntax. e.g. ((${#array[@]} < something)).

    Additionally, since you are calling a script that requires root privileges to call shutdown, you should test for root EUID at the beginning:

    if ((EUID != 0)); then
        printf "error: script must be run by root, EUID: '%s' can't.\n" $EUID
        exit 0
    fi
    

    or if you prefer the normal [ test construct:

    if [ $EUID -ne 0 ]; then
    ...