How do you echo a 4-digit Unicode character in Bash?

后端 未结 18 1991
醉梦人生
醉梦人生 2020-11-29 14:38

I\'d like to add the Unicode skull and crossbones to my shell prompt (specifically the \'SKULL AND CROSSBONES\' (U+2620)), but I can\'t figure out the magic incantation to m

18条回答
  •  遥遥无期
    2020-11-29 15:21

    Sorry for reviving this old question. But when using bash there is a very easy approach to create Unicode codepoints from plain ASCII input, which even does not fork at all:

    unicode() { local -n a="$1"; local c; printf -vc '\\U%08x' "$2"; printf -va "$c"; }
    unicodes() { local a c; for a; do printf -vc '\\U%08x' "$a"; printf "$c"; done; };
    

    Use it as follows to define certain codepoints

    unicode crossbones 0x2620
    echo "$crossbones"
    

    or to dump the first 65536 unicode codepoints to stdout (takes less than 2s on my machine. The additional space is to prevent certain characters to flow into each other due to shell's monospace font):

    for a in {0..65535}; do unicodes "$a"; printf ' '; done
    

    or to tell a little very typical parent's story (this needs Unicode 2010):

    unicodes 0x1F6BC 32 43 32 0x1F62D 32 32 43 32 0x1F37C 32 61 32 0x263A 32 32 43 32 0x1F4A9 10
    

    Explanation:

    • printf '\UXXXXXXXX' prints out any Unicode character
    • printf '\\U%08x' number prints \UXXXXXXXX with the number converted to Hex, this then is fed to another printf to actually print out the Unicode character
    • printf recognizes octal (0oct), hex (0xHEX) and decimal (0 or numbers starting with 1 to 9) as numbers, so you can choose whichever representation fits best
    • printf -v var .. gathers the output of printf into a variable, without fork (which tremendously speeds up things)
    • local variable is there to not pollute the global namespace
    • local -n var=other aliases var to other, such that assignment to var alters other. One interesting part here is, that var is part of the local namespace, while other is part of the global namespace.
      • Please note that there is no such thing as local or global namespace in bash. Variables are kept in the environment, and such are always global. Local just puts away the current value and restores it when the function is left again. Other functions called from within the function with local will still see the "local" value. This is a fundamentally different concept than all the normal scoping rules found in other languages (and what bash does is very powerful but can lead to errors if you are a programmer who is not aware of that).

提交回复
热议问题