For a list of BASHing data 2 blog posts see the index page.
Print a character as a variable with BASH printf
The default printf on my system is the BASH built-in command:
and it happily prints characters in "universal character name" format, uNNNN:
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:
Nope, that doesn't work. The correct format specifier to use in this case is %b, which understands backslash escapes:
But I get the same result if I don't have a separate argument, with less typing:
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:
Note that if you want to concatenate the variable with a string, the variable needs to be isolated with curly brackets:
Printing a character as a variable can also be done both ways with GNU "coreutils" printf, which is a separate program on my system:
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