banner

For a list of BASHing data 2 blog posts see the index page.    RSS


Print a character as a variable with BASH printf

The default printf on my system is the BASH built-in command:

printf1

and it happily prints characters in "universal character name" format, uNNNN:

printf2

In some of my functions and scripts I take user input as "uNNNN" without the leading backslash, and store it in a variable. I then want to print the corresponding character from that variable with printf. There are a couple of ways to do this, one of which is the safer one.

The safe, recommended method is to print a variable as an argument for printf, with any modifiers for the variable included in the format specifier. Noting that the character "\" needs to be escaped as "\\", I'll try that:

printf3

Nope, that doesn't work. The correct format specifier to use in this case is %b, which understands backslash escapes:

printf4

But I get the same result if I don't have a separate argument, with less typing:

printf5

My alternative construction is widely regarded as a bad idea, for example in this Stack Overflow thread from 2022, but it seems to work for printing isolated characters specified as character codes:

printf6

Note that if you want to concatenate the variable with a string, the variable needs to be isolated with curly brackets:

printf7

Printing a character as a variable can also be done both ways with GNU "coreutils" printf, which is a separate program on my system:

printf8

To see the documentation for the BASH built-in printf, enter help printf or printf --help.
 
For the "coreutils" printf documentation, enter man printf.


Last update: 2024-03-22
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License