How do I set a variable with color and left align with bash
Example:
red=$(tput setaf 1)
green=$(tput setaf 2)
normal=$(tput sgr0)
if [ $process_state != "running" ]; then
process_state=${red}$process_state${normal}
else
process_state=${green}$process_state${normal}
fi
printf "%-10s|" $process_state
Inputs
process_state=running
process_state=stopped
Output
running | <-- Where this is in green
stopped | <-- Where this is in red
*** UPDATED *** Solution:
red=$(tput setaf 1)
green=$(tput setaf 2)
normal=$(tput sgr0)
if [ $process_state != "running" ]; then
process_state="${red} $process_state ${normal}"
else
process_state="${green} $process_state ${normal}"
fi
printf "%s%-10s%s|" $process_state
Note: Notice the spaces around $process_state separating it from color.
There will be a problem with the computation of the width of the field in the way you are doing it because $red
and $green
do not have a zero width for printf.
I would recode in the next way:
red=$(tput setaf 1)
green=$(tput setaf 2)
normal=$(tput sgr0)
if [ "$process_state" != "running" ]; then
printf "%s%-10s%s|" "$red" "$process_state" "$normal"
else
printf "%s%-10s%s|" "$green" "$process_state" "$normal"
fi