2

I have a script on my mac that displays the battery level with some color output. The color is based on the battery leve. As the level goes to zero, the color goes from green to red:

#!/bin/bash

percent=`ioreg -l | grep -i capacity | tr '\n' ' | ' | awk '{printf("%d", $10/$5 * 100)}'`
if [ $percent -gt 80 ] ; then
  echo -n $'\e[32m'"${percent}%"
elif [ $percent -gt 65 ] ; then
  echo -n $'\e[1;33m'"${precent}%"
elif [ $percent -gt 40 ] ; then
  echo -n $'\e[1;31m'"${percent}%"
else
  echo -n $'\e[31m'"${percent}%"
fi

I have put this in my tmux config as:

# status right options
set -g status-right '#[fg=green][#[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default]  #($HOME/bin/battery)#[fg=green]]'

However, it shows up in my terminal as:

enter image description here

My question is, how can I get tmux to display the escape character correctly?

1 Answer 1

3

This does not seem to be documented, but the output of #() shell-commands in status-left, status-right, window-status-format, and window-status-current-format is also processed for #[] color/attribute sequences.

So, just output the #[] sequences instead of the escape sequences.

#!/bin/bash
percent=$(ioreg …)
if   (( percent > 80 )); then color='#[nobright fg=green]'
elif (( percent > 65 )); then color='#[bright fg=yellow]'
elif (( percent > 40 )); then color='#[bright red]'
                         else color='#[nobright red]'
fi
echo "$color$percent%"

It makes sense that full escape sequences are not interpreted for these status strings: there is not much point to doing (e.g.) cursor control since they are always rendered into (part of) a single line.


I ended up browsing through the source code to find that #[] is interpreted strictly after all other # sequences (including #()). It looks like this has always been the case since #[] was introduced.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .