0

I am trying to right-align coloured text with a given field width.

Based on right text align - bash and Using colors with printf I don't understand the output of:

blue=$(tput setaf 4)
normal=$(tput sgr0)

printf "%4s\n" "${blue}aaa${normal}"

blue=$(tput setaf 4)
normal=$(tput sgr0)

printf "%10s\n" "${blue}aaa${normal}"

blue=$(tput setaf 4)
normal=$(tput sgr0)

printf "%40s\n" "${blue}aaa${normal}"

blue=$(tput setaf 4)
normal=$(tput sgr0)

printf "%8s\n" "${blue}aaa${normal}"

which is:

aaa
aaa
                          aaa
aaa

why are entries 1,2 and 4 left-aligned?

Thanks!

GNU bash, version 4.4.23(1)-release (x86_64-redhat-linux-gnu)

PintoDoido
  • 1,011
  • 16
  • 35
  • They aren't. The color sequences take up space. If the string is longer than the width of the format specified, then no padding is added to the start of the string. Each of your strings is longer than the specified width. – William Pursell Jul 18 '19 at 15:00
  • thanks! mistery solved – PintoDoido Jul 18 '19 at 15:08
  • 2
    Probably cleaner to write: `printf "%s%8s%s" "$blue" "aaa" "$normal"` – William Pursell Jul 18 '19 at 15:10
  • Thanks! is the field specifier taken into account before or after the expansion? – PintoDoido Jul 18 '19 at 15:21
  • No need to repeat the assignments. To answer your question, the variables are expanded then the results of the expansions are passed through the format. That's why you were getting the results you saw. – Dennis Williamson Jul 18 '19 at 23:47
  • Hum.. so why printf "%15b\n" "${blue}aaa${normal}" starts getting extra space? After all there are 9+12+3 characters involved after the expansion! – PintoDoido Jul 19 '19 at 07:45

0 Answers0