Skip to content
Advertisement

Linux bash printf format with color assign to variable

I just want a String (including coloring) be formatted by printf command and assign the result to a variable.

Without assigning it to a variable it works fine, but as soon as I assign the result to a variable and write the result, the format is gone.

My example:

RED=$'33[0;31m'
NC=$'33[0m'

INPUT="AB${RED}CD${NC}EF"

printf -v OUTPUT '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST "
echo $OUTPUT

OUTPUT="$(printf  '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST ")"
echo $OUTPUT

OUTPUT=$(printf  '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST ")
echo $OUTPUT

printf '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST "
echo ""

I found several solutions for passing the result to a variable (-v VARIABLE), but it looses the format.

Thanks for your help and many greetings,

Hauke

EDIT 1: Also one problem seems to be the colorcode. printf counts AB${RED}CD${NC}EF as 17 characters instead of 6.

Advertisement

Answer

Use this (echo “$VAR” in “”) to keep the formatting. The different ways of assigning the variable make no difference:

printf -v OUTPUT '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST "
# or
OUTPUT=$(printf  '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST ")
echo "$OUTPUT"
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement