Eu tenho uma função em um script bash: message_offset , que é usado para imprimir o status de um script bash.
ou seja, você chamaria de passar uma mensagem para ele e um status, como este
message_offset "install font library" "[ OK ]"
e imprimiria no terminal onde o formato printf %*s é usado para sempre definir o caractere mais à direita de [ OK ] em 80 colunas de largura
por exemplo. saída seria
install font library [ OK ]
update configuration file on server [ ERR ]
^
|
always
at 80
Se echo foi usado, a saída ficaria assim
install font library [ OK ]
update configuration file on server [ ERR ]
código:
#!/usr/bin/env bash
function message_offset() {
local message="$1"
local status="$2"
# compensate for the message length by reducing the offset
# by the length of the message,
(( offset = 80 - ${#message} ))
# add a $(tput sgr0) to the end to "exit attributes" whether a color was
# set or not
printf "%s%*s%s" "${message}" 80 "$status" "$(tput sgr0)"
}
tudo isso funciona ok, até eu tentar usar tput para adicionar algumas seqüências de cores na string, ou seja, para fazer "[ERR]" vermelho.
Parece que a formatação printf "%*s" está contando
as seqüências de caracteres tput quando sua configuração do deslocamento, por isso, se eu chamar a função como esta
message_offset "update configuration file on server" "$(tput setaf 1)[ ERR ]"
a saída será parecida com:
install font library [ OK ]
update configuration file on server [ ERR ]
porque printf "%*s" está dizendo hey essa string tem todos os caracteres "[ ERR ]" , mais os caracteres "$(tput setaf 1) , mas obviamente os caracteres "$(tput setaf 1) não são impressos, portanto, na verdade, não afeta o preenchimento. >
Existe uma maneira de adicionar cores às mensagens de "status" e também usar as seqüências de cores do estilo tput ?