Problem with printf width field formatting - bash

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)

Related

tput is very slow on MinTTY (Git Bash)

Git Bash is pretty sluggish overall (compare 1.082s of average runtime under WSL/Ubuntu vs 4.460s in MinTTY). I've narrowed down a whopping 1.479s to the following chunk of code:
# Determine if this terminal supports colors
if test -t 1; then
if [[ -n "$(tput colors)" ]] && [[ "$(tput colors)" -ge 8 ]]; then
MY_APP_FMT_SUPPORTED=true
MY_APP_FMT_BOLD="$(tput bold)"
MY_APP_FMT_UNDERLINE="$(tput smul)"
MY_APP_FMT_INVERSE="$(tput smso)"
MY_APP_FMT_BLACK="$(tput setaf 0)"
MY_APP_FMT_RED="$(tput setaf 1)"
MY_APP_FMT_GREEN="$(tput setaf 2)"
MY_APP_FMT_YELLOW="$(tput setaf 3)"
MY_APP_FMT_BLUE="$(tput setaf 4)"
MY_APP_FMT_MAGENTA="$(tput setaf 5)"
MY_APP_FMT_CYAN="$(tput setaf 6)"
MY_APP_FMT_WHITE="$(tput setaf 7)"
MY_APP_FMT_CODE=$MY_APP_FMT_CYAN
# placing it down below so that option -x doesn't cause bad highlighting
# to persist
MY_APP_FMT_CLEAR="$(tput sgr0)"
fi
fi
Given my understanding of the performance of *nix tools on Windows, I suspect the slowdown is from all the subshells.
Should these subshells explain the entire slowdown? If not, I'll need to continue researching why Git Bash is still sluggish.
Is there a more performant way to do this while maintaining terminal compatibility?
You can group tput calls by using -S option:
#!/usr/bin/env bash
tkeys=(bold smul "setaf 0" "setaf 1") # You can add the rest
tvalues_s=$(tput -S < <(printf "%s\n" "${tkeys[#]}"))
declare -a tvalues=( ${tvalues_s//$'\e'/ $'\e'} )
declare -p tvalues
Now that you have values in tvalues, which you can assign to MY_APP_FMT_...

How can I clean a string in bashrc?

I'd like to know how to "clean up" a line of code in bash. I've created a string to colour the command line in my ~/.bashrc which looks like this:
PS1='\[\033[1;36m\]\u\[\033[1;31m\]#\[\033[1;32m\]\h:\[\033[1;35m\]\w\[\033[1;31m\]\$\[\033[0m\] '
I'd like to make it easier to discern. More something along these lines:
PS1='\[\033[1;36m\]
\u\[\033[1;31m\]
#\[\033[1;32m\]
\h:\[\033[1;35m\]
\w\[\033[1;31m\]
\$\[\033[0m\] '
I've tried putting these {} brackets but that didn't seem to work, either.
EDIT: thanks to tripleee. The code that works is as follows:
tprompt () {
local bold=$(tput bold)
local red=$(tput setaf 1)
local green=$(tput setaf 2)
local magenta=$(tput setaf 5)
local cyan=$(tput setaf 6)
local plain=$(tput sgr0)
printf -v PS1 "%s" "$bold" "$cyan" '\u' \
"$red" "#" \
"$green" '\h:' \
"$magenta" '\w' \
"$red" '\$' \
"$plain"
}
tprompt
A better overall approach might be to use tput to generate these codes, rather than hard-code them for a specific terminal. This also allows you to assign mnemonic names to them.
tprompt () {
local bold=$(tput bold)
local red=$(tput setaf 1)
local green=$(tput setaf 2)
local magenta=$(tput setaf 5)
local cyan=$(tput setaf 6)
local plain=$(tput sgr0)
printf -v PS1 "%s" "$bold" "$cyan" '\u' \
"$red" "#" \
"$green" '\h:' \
"$magenta" '\w' \
"$red" '\$' \
"$plain" ' '
}
tprompt
(Not sure I managed to correctly map back the escape codes to their meanings, but you should at least be able to see how this is more readable and maintainable than what you had. The sole reason to define a function for this is to create a local scope so the helper variables don't pollute the global namespace. We only call the function once; you could even undefine the function when you have called it, too.)
As an aside, notice also how printf lets you easily paste together multiple strings. Even if you don't adopt this approach wholesale, you might want to refactor to
printf -v PS1 '%s' \
'\[\033[1;36m\]' \
'\u\[\033[1;31m\]' \
'#\[\033[1;32m\]' \
'\h:\[\033[1;35m\]' \
'\w\[\033[1;31m\]' \
'\$\[\033[0m\] '
As a final aside, non-printing sequences in the prompt should be wrapped in \[ ... \] to tell Bash to disregard them when calculating the line length. Maybe wrap tput with a function, too:
tput () {
printf '\\['
command tput "$#"
printf '\\]'
}

How to print a string in color, when a Variable has the actual color name?

I am trying to print a string with Specific color depending on the error code. Color varies on each error code, I am storing the actual color name in variable and using it in printf.
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
BLUE=$(tput setaf 4)
CYAN=$(tput setaf 5)
BOLD=$(tput bold)
NORMAL=$(tput sgr0)
# this color varies depending on error code
color=GREEN
printf "\${$color} This is a String ${NORMAL} \n"
But I get output as
${GREEN} This is a String
Expected output(In actual Green color)
This is a String
I can get this using
printf "${GREEN} This is a String ${NORMAL} \n"
But I want this output using color variable
Bash doesn't treat ${<variable>} recursively inside strings, as you tried to do.
You can do color=$<colorVariable>, ie color=$GREEN before the printf, and then in the printf string doing "$color This is a String ${NORMAL} \n"
So, final result:
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
BLUE=$(tput setaf 4)
CYAN=$(tput setaf 5)
BOLD=$(tput bold)
NORMAL=$(tput sgr0)
# Event-dependant color
color=$GREEN
# And finally,
printf "$color This is a String ${NORMAL} \n"
There's another way you can do it.
# Define all colors, only GREEN and NORMAL here for brevity reasons
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)
# Notice the missing $, as the original question
color=GREEN
# And then, use Bash's variable reference method (here notice both ! instead of $ and the missing \ at the beginning
printf "${!color} This is a String ${NORMAL} \n"
How about:
color=$GREEN
And then:
printf "$color This is a String ${NORMAL} \n"
Gives me:
This is a String
in green.

How to show all colors supported by bash?

One day, I typed the command
echo "\033[32mHELLOBASE\033[m"
in the gnome bash shell. The terminal showed me a green HELLOBASH string.
I found this interesting. From my experience and serveral tests, I can change
the number 32 from 0 up to 47. Next I wrote the following code,
for i in {0..48};do
echo \033[$imHELLOBASH\[033m
done
Of course, it doesn't work, or I cannot be here! So how to improve the above code to function?
Let's do this the right way -- looking up color codes in our termcap (or, for modern systems, terminfo) database using the tput command:
for ((i=0; i<=48; i++)); do
tput setaf "$i"
echo HELLOBASH
done
If you want to see all available colors on a 256-color terminal, use this code token from BashFAQ #37:
colors256() {
local c i j
printf "Standard 16 colors\n"
for ((c = 0; c < 17; c++)); do
printf "|%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n\n"
printf "Colors 16 to 231 for 256 colors\n"
for ((c = 16, i = j = 0; c < 232; c++, i++)); do
printf "|"
((i > 5 && (i = 0, ++j))) && printf " |"
((j > 5 && (j = 0, 1))) && printf "\b \n|"
printf "%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n\n"
printf "Greyscale 232 to 255 for 256 colors\n"
for ((; c < 256; c++)); do
printf "|%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n"
}
colors256
For additional background on how and why any of this works, see the bash-hackers page on terminal codes.
As for why your original code didn't work even on terminals using ANSI color codes, by the way -- #rici pegged it correctly: Your parameter expansion was ambiguous without adding curly braces.
That is to say:
$imHELLOBASH
...needed to be...
${i}mHELLOBASH
...to avoid the shell trying to find and expand a variable called imHELLOBASH rather than a variable named i.
It is not much to do with bash, more to do with the terminal driver. Rather than trying to use control characters, I suggest you use tput instead, for example:
i=1
while (( $i < 10 ))
do
tput setaf $i
echo "This is $i"
(( i++ ))
done

How to right align and left align text strings in Bash

I'm creating a bash script and would like to display a message with a right aligned status (OK, Warning, Error, etc) on the same line.
Without the colors, the alignment is perfect, but adding in the colors makes the right aligned column wrap to the next line, incorrectly.
#!/bin/bash
log_msg() {
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)
MSG="$1"
let COL=$(tput cols)-${#MSG}
echo -n $MSG
printf "%${COL}s" "$GREEN[OK]$NORMAL"
}
log_msg "Hello World"
exit;
I'm not sure why it'd wrap to the next line -- having nonprinting sequences (the color changes) should make the line shorter, not longer. Widening the line to compensate works for me (and BTW I recommend using printf instead of echo -n for the actual message):
log_msg() {
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)
MSG="$1"
let COL=$(tput cols)-${#MSG}+${#GREEN}+${#NORMAL}
printf "%s%${COL}s" "$MSG" "$GREEN[OK]$NORMAL"
}
You have to account for the extra space provided by the colors.
log_msg() {
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)
MSG="$1"
STATUS="[OK]"
STATUSCOLOR="$GREEN${STATUS}$NORMAL"
let COL=$(tput cols)-${#MSG}+${#STATUSCOLOR}-${#STATUS}
echo -n $MSG
printf "%${COL}s\n" "$STATUSCOLOR"
}

Resources