%B
and %b
are examples of prompt sequences, and usually can only be used for formatting prompts. For normal scripting, you can use the tput
command to achieve what you want:
echo "$(tput bold)$1$(tput sgr0)"
Alternatively, you could output the ECMA-48 ("ANSI") escape codes directly. I wouldn't recommend this though, because it's less portable across terminals. (It's quite hard, nowadays in the 21st century, to encounter a terminal that doesn't implement ECMA-48 and the basic ECMA-48 SGR features like boldface, but since you are challenging yourself to learn this, you should learn that terminals do not have the guarantee of understanding exactly the same control sequences as one another. You should also learn that there still remain a few terminal emulators where boldface is a colour change and not a font weight change.)
echo $'\e[1m'"$1"$'\e[22m'
Notice the use of Korn-style quoting for the control sequences.
In the general case, the echo
command may or may not itself interpret \e
sequences if not Korn-style quoted and such escape sequences work differently in different shells, or even different versions of the same shell; and conversely not all shells understand Korn-style quoting.
See "Why is printf better than echo?" for the whole tale and why echo
is not a good idea if you are addressing anything other than a single specific (version of a) shell.
printf '\e[1m%s\e[22m' "$1"
Notice that SGR 0 (corresponding to \e[0m
, which is what tput sgr0
also usually nowadays emits) turns off everything, which may not be what you want if you are also using underlining, italics, colours, reverse video, or other graphic renditions.
To turn off boldface specifically, SGR 22 is the graphic rendition code, which turns off boldface and faint, restoring "medium" font weight. (The Set Graphic Rendition control sequence lets you set four font weights: bold, demibold, medium, and light.)
Since you are using the Z shell, you can also use its own built-in print
command instead of using echo
or printf
at all.
The built-in print
can be told to understand Z shell prompt expansion sequences:
print -P '%B'"$1"'%b'
Of course, your $1
string must not contain other expansion sequences itself, nor indeed any SGR control sequences for changing boldface.
And this won't give you the challenge of learning tput
and how terminfo capabilities work.
{}
just group commands, they don't create subshells. – guest Aug 02 '20 at 08:04