Search code examples
shellreturn-valuezshzshrc

Print a file in zsh


I am writing my .zshrc. I want my prompt to show my battery level which is stored in /sys/class/power_supply/BAT0/capacity I wrote a function that will take the value from the file and change the color of the digits (green if it is greater than 50, orange if greater than 20, and red otherwise.

The problem is I get this:

/home/user/.zshrc:5: parse error: condition expected: $getPower

My zshrc shows this for the $getPower function

3 function getPower ()
4 {
5     cat /sys/class/power_supply/BAT0/capacity
6 }
7 function batteryLeft  ()
8 {
9     if [[ getPower > 50 ]]; then
10        echo "Phrase"
11    fi
12}

On ZSH Documentation the first 2 code samples have 2 different ways to declare a function, with a function keyword and one without. Not sure what the problem is.


Solution

  • Notably, nothing in this code is zsh-specific -- all the extensions used below are present in ksh93 and bash as well.

    getPower() { cat /sys/class/power_supply/BAT0/capacity; }
    
    batteryLeft() {
        if (( $(getPower) > 50 )); then
            echo "Phrase"
        fi
    }
    
    • The function keyword makes your code incompatible with baseline-POSIX shells while adding no advantage over the compatible syntax. Avoid it as a matter of good practice.
    • To run your function, and thus be operating on its output, you need a command substitution, such as $().
    • To be running a numeric comparison rather than a string comparison, you need to either use (( )) in place of [[ ]], or use -gt in place of >. (This is incompatible with baseline POSIX -- you'd need to use [ "$(getPower)" -gt 50 ] to work with other shells -- but also has compensating advantages).