来个有趣的Terminal motd吧

2021年12月22日 · 2 years ago

来个有趣的Terminal motd吧

程序员大都离不开终端(Terminal),之前我写过一个 macOS 效率系列,还有这篇文章都提到这个黑漆漆的窗口。

本文给大家介绍一下每次我的 Terminal 打开之后会展示的欢迎信息 motd

一、简单静态文本

motd 是 Message of the Day 的缩写,大部分 Unix-like 系统都有这个 feature。原理很简单,就是在 shell login 之前一刻,把 /etc/motd 这个文件打印出来。macOS 的这部分实现在 system_cmds 里:

/*
* Display the contents of a file (such as /etc/motd).
*/
static int
motd(const char *motdfile)
{
sig_t oldint;
FILE *f;
int ch;

if ((f = fopen(motdfile, "r")) == NULL)
return (-1);
motdinterrupt = 0;
oldint = signal(SIGINT, sigint);
while ((ch = fgetc(f)) != EOF && !motdinterrupt)
putchar(ch);
signal(SIGINT, oldint);
if (ch != EOF || ferror(f)) {
fclose(f);
return (-1);
}
fclose(f);
return (0);
}

只要修改 /etc/motd 文件,往里面放你喜欢的文本,它就会自动打印出来啦。

比如说想要打印出 JUSTIN 的 ASCII ART 形式,那我们可以到这里把你想要打印的文本转成 ASCII Text,粘贴到 motd 文件即可。

二、天天都有彩虹新花样

如果要动态生成文本,带点小花样,最好来个 RGB 艺术呢?😂

motd 本身只是个纯文本,不支持执行 shell script,所以我们可以考虑在 ~/.profilezsh 用户可修改 ~/.zshrc)里调用一个 shell script 来打印内容。

首先我们使用 FIGlet 把纯文本变成 ASCII Text:

brew install figlet

echo "JUSTIN" | figlet

figlet 可以选择多种字体,可以参考这里

Font: banner3
## ## ####### #######
### ### ## ## ## ##
#### #### ## ## ## ##
## ### ## ## ## ## ##
## ## ## ## ## ##
## ## ## ## ## ##
## ## ####### #######

Font: isometric1
___ ___ ___
/\__\ /\ \ /\ \
/::| | /::\ \ /::\ \
/:|:| | /:/\:\ \ /:/\:\ \
/:/|:|__|__ /:/ \:\ \ /:/ \:\ \
/:/ |::::\__\ /:/__/ \:\__\ /:/__/ \:\__\
\/__/~~/:/ / \:\ \ /:/ / \:\ \ /:/ /
/:/ / \:\ /:/ / \:\ /:/ /
/:/ / \:\/:/ / \:\/:/ /
/:/ / \::/ / \::/ /
\/__/ \/__/ \/__/

然后我们再用 cowsay 把小牛加上去

brew install cowsay
echo "Hello World!" | cowsay

cowsay 默认是一头小牛,自带多种动物可以选择,比如来一头堕拉贡:

___________
< different >
-----------
\ / \ //\
\ |\___/| / \// \\
/0 0 \__ / // | \ \
/ / \/_/ // | \ \
@_^_@'/ \/_ // | \ \
//_^_/ \/_ // | \ \
( //) | \/// | \ \
( / /) _|_ / ) // | \ _\
( // /) '/,_ _ _/ ( ; -. | _ _\.-~ .-~~~^-.
(( / / )) ,-{ _ `-.|.-~-. .~ `.
(( // / )) '/\ / ~-. _ .-~ .-~^-. \
(( /// )) `. { } / \ \
(( / )) .----~-.\ \-' .~ \ `. \^-.
///.----..> \ _ -~ `. ^-` ^-_
///-._ _ _ _ _ _ _}^ - - - - ~ ~-- ,.-~
/.-~

还可以选择是 cowsay 还是 cowthink。我的做法是随机生成一只动物:

cowsay -f $(cd /opt/homebrew/Cellar/cowsay/3.04_1/share/cows && ls *.cow | shuf -n1)

中间的 cows path 需要自己找出来,只选 *.cow 是因为 .pm 的 cowfile 会解析失败。另外用到一个随机 shuffle 的命令 shuf 需要额外安装 coreutils

brew install coreutils

效果还不错,但是 RGB 彩虹效果不能妹有啊,用 lolcat 整起来:

brew install lolcat
echo "Hello World" | cowsay | lolcat

很好,我们再加点动画:

echo "Hello World" | cowsay | lolcat --animate -s 1000

Woohoo! 不过每次都显示 "Hello World!" 也太单调了,再加一个 fortune,天天都有不同的 fortune cookie:

fortune | cowsay | lolcat --animate -s 1000

最终效果如下:

我创建了一个 gist,有兴趣的朋友可以参考看一下。