3

I want to print bold text using printf. How do I do it?

printf '%s\n' "\033[1m"bold_text"\033[0m"

doesn't work. It displays:

\033[1mbold_text\033[0m

However, the same string works fine with echo -e:

echo -e "\033[1m"bold_text"\033[0m"
bold_text
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • https://stackoverflow.com/q/2924697/5291015 ? (not my dv) – Inian Aug 27 '20 at 06:49
  • `printf "\e[1;mbold_text\n\e[0m"` – Maroun Aug 27 '20 at 06:52
  • I'd never hardcode escape sequences. Use the terminal capabilities. – Ted Lyngmo Aug 27 '20 at 06:53
  • @oguz I'd rather prefer you add it to the https://stackoverflow.com/questions/2924697/how-does-one-output-bold-text-in-bash post to make it a generic duplicate covering all cases – Inian Aug 27 '20 at 06:57
  • 1
    I meant, people who are looking for way to use printf can use your answer. So that can be made a canonical duplicate in the future – Inian Aug 27 '20 at 06:59
  • `printf '%b\n' ` did the trick. The linked answers seem to use `echo -e` everywhere. I had seen those post before adding this question. – codeforester Aug 27 '20 at 07:22
  • Not sure why the question should be downvoted. When I searched for `bash printf bold` nothing good showed up on the site and hence I posted it as a new question. – codeforester Aug 27 '20 at 07:23

1 Answers1

8

The right answer is to use the %b format specifier instead of %s:

printf '%b\n' "\033[1m"bold_text"\033[0m"

From help printf:

%b - expand backslash escape sequences in the corresponding argument

codeforester
  • 39,467
  • 16
  • 112
  • 140