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

后端 未结 18 1798
醉梦人生
醉梦人生 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 14:56

    If you don't mind a Perl one-liner:

    $ perl -CS -E 'say "\x{2620}"'
    ☠
    

    -CS enables UTF-8 decoding on input and UTF-8 encoding on output. -E evaluates the next argument as Perl, with modern features like say enabled. If you don't want a newline at the end, use print instead of say.

    0 讨论(0)
  • 2020-11-29 14:56

    Easy with a Python2/3 one-liner:

    $ python -c 'print u"\u2620"'    # python2
    $ python3 -c 'print(u"\u2620")'  # python3
    

    Results in:

    0 讨论(0)
  • 2020-11-29 15:02

    In bash to print a Unicode character to output use \x,\u or \U (first for 2 digit hex, second for 4 digit hex, third for any length)

    echo -e '\U1f602'
    

    I you want to assign it to a variable use $'...' syntax

    x=$'\U1f602'
    echo $x
    
    0 讨论(0)
  • 2020-11-29 15:05

    In UTF-8 it's actually 6 digits (or 3 bytes).

    $ printf '\xE2\x98\xA0'
    ☠
    

    To check how it's encoded by the console, use hexdump:

    $ printf ☠ | hexdump
    0000000 98e2 00a0                              
    0000003
    
    0 讨论(0)
  • 2020-11-29 15:06

    So long as your text-editors can cope with Unicode (presumably encoded in UTF-8) you can enter the Unicode code-point directly.

    For instance, in the Vim text-editor you would enter insert mode and press Ctrl + V + U and then the code-point number as a 4-digit hexadecimal number (pad with zeros if necessary). So you would type Ctrl + V + U 2 6 2 0. See: What is the easiest way to insert Unicode characters into a document?

    At a terminal running Bash you would type CTRL+SHIFT+U and type in the hexadecimal code-point of the character you want. During input your cursor should show an underlined u. The first non-digit you type ends input, and renders the character. So you could be able to print U+2620 in Bash using the following:

    echo CTRL+SHIFT+U2620ENTERENTER

    (The first enter ends Unicode input, and the second runs the echo command.)

    Credit: Ask Ubuntu SE

    0 讨论(0)
  • 2020-11-29 15:06

    I'm using this:

    $ echo -e '\u2620'
    ☠
    

    This is pretty easier than searching a hex representation... I'm using this in my shell scripts. That works on gnome-term and urxvt AFAIK.

    0 讨论(0)
提交回复
热议问题