0

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.

Ryan Harlich
  • 157
  • 1
  • 7

1 Answers1

3

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
Pierre François
  • 5,850
  • 1
  • 17
  • 38
  • 3
    Suggestion for improvement: add quotes around `$process_state` in the `if` statement in case `process_state` is empty. – rtx13 Apr 01 '20 at 19:31
  • 1
    Thanks for the help. I added the solution of what I was looking for in the question. – Ryan Harlich Apr 01 '20 at 20:49