I've been diving into the different ways to print text in Bash after seeing a comment about printf. Typically, I just print error messages, but with my recent loss of my 13-year-old dog, I've been taking on some small projects as a distraction.
I'm trying to figure out how to use a HEREDOC with colored text. I know that `cat` is commonly used for HEREDOC, but when I attempt to change the font color using escape sequences like `33[0;31m`, the output shows the literal text instead of coloring it.
Here's a little snippet of what I've been working on:
cat << EOF
33[0;31m Whatever, dude 33[0m
EOF
I also looked into using `tput` or `echo -e` to create variables for color:
RED=$(tput setaf 1)
NORM=$(tput sgr0)
cat << EOF
${RED}Whatever, dude${NORM}
EOF
Are there better or different methods to achieve colored output in HEREDOCs than what I've mentioned?
3 Answers
I prefer using `printf` for these cases. You could do something like this:
```
printf "e[1;31mThis is bold red.e[0m"
```
It works smoothly for me, especially when dealing with multi-line prints.
I found another useful way to handle color with HEREDOCs using `hd_color`. Here's how you can do it:
```
hd_color red <<EOF
whatever, dude
EOF
```
And you can set it for other colors like blue too. Just a tip, it would be great if these functions were global so you don't have to redefine them in every script!
You can also define colors using variables like this:
```
red=$'e[31m'
off=$'e[0m'
```
All the escape sequence representations (like `e`, `33`, etc.) work similarly. Just a quick note: it's good practice to use lower case for your variables rather than upper case, as the latter is usually reserved for environment variables.
Same here! I usually go for `printf`, but I've been working on scripts with multi-line prints lately, so I'm keen on improving how I do it.