我想将Unicode头骨和交叉骨头添加到我的shell提示符(特别是' skull and crossbones ' (U+2620)),但我不知道让echo吐出它的魔法咒语,或任何其他4位Unicode字符。两位数的数字很简单。例如echo -e "\x55",。

除了下面的答案之外,还应该注意到,很明显,您的终端需要支持Unicode以使输出符合您的期望。Gnome-terminal在这方面做得很好,但它在默认情况下不一定是打开的。

在macOS的终端应用程序中,选择首选项->编码,并选择Unicode (UTF-8)。


当前回答

printf内置(就像coreutils的printf一样)知道接受4位Unicode字符的\u转义序列:

   \uHHHH Unicode (ISO/IEC 10646) character with hex value HHHH (4 digits)

使用Bash 4.2.37(1)测试:

$ printf '\u2620\n'
☠

其他回答

简单地使用Python2/3一行代码:

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

结果:

只需在shell脚本中输入“☠”。在正确的地区和支持unicode的控制台上,它可以正常打印:

$ echo ☠
☠
$

一个丑陋的“变通方法”是输出UTF-8序列,但这也取决于所使用的编码:

$ echo -e '\xE2\x98\xA0'
☠
$

这是一个完全内部的Bash实现,没有分叉,Unicode字符大小不限。

fast_chr() {
    local __octal
    local __char
    printf -v __octal '%03o' $1
    printf -v __char \\$__octal
    REPLY=$__char
}

function unichr {
    local c=$1    # Ordinal of char
    local l=0    # Byte ctr
    local o=63    # Ceiling
    local p=128    # Accum. bits
    local s=''    # Output string

    (( c < 0x80 )) && { fast_chr "$c"; echo -n "$REPLY"; return; }

    while (( c > o )); do
        fast_chr $(( t = 0x80 | c & 0x3f ))
        s="$REPLY$s"
        (( c >>= 6, l++, p += o+1, o>>=1 ))
    done

    fast_chr $(( t = p | c ))
    echo -n "$REPLY$s"
}

## test harness
for (( i=0x2500; i<0x2600; i++ )); do
    unichr $i
done

输出是:

─━│┃┄┅┆┇┈┉┊┋┌┍┎┏
┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟
┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯
┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿
╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏
═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟
╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯
╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿
▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏
▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟
■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯
▰▱▲△▴▵▶▷▸▹►▻▼▽▾▿
◀◁◂◃◄◅◆◇◈◉◊○◌◍◎●
◐◑◒◓◔◕◖◗◘◙◚◛◜◝◞◟
◠◡◢◣◤◥◦◧◨◩◪◫◬◭◮◯
◰◱◲◳◴◵◶◷◸◹◺◻◼◽◾◿

printf内置(就像coreutils的printf一样)知道接受4位Unicode字符的\u转义序列:

   \uHHHH Unicode (ISO/IEC 10646) character with hex value HHHH (4 digits)

使用Bash 4.2.37(1)测试:

$ printf '\u2620\n'
☠

在bash中打印Unicode字符输出使用\x,\u或\u(第一个用于2位十六进制,第二个用于4位十六进制,第三个用于任何长度)

echo -e '\U1f602'

如果你想把它赋值给一个变量,使用$'…的语法

x=$'\U1f602'
echo $x