Mic*_*ant 6 colors tail function head
多亏了其他人,我的“彩色猫”工作得很好
(请参阅如何为 cat 输出着色,包括黑白中的未知文件类型?)。
在我的.bashrc
:
cdc() {
for fn in "$@"; do
source-highlight --out-format=esc -o STDOUT -i $fn 2>/dev/null || /bin/cat $fn;
done
}
alias cat='cdc' # To be next to the cdc definition above.
Run Code Online (Sandbox Code Playgroud)
我希望能够将此技术用于其他功能,例如 head、tail 和 less。
我怎么能对所有四个功能都做到这一点?有什么方法可以概括答案吗?
我有一个选择gd
做git diff
使用
gd() {
git diff -r --color=always "$@"
}
Run Code Online (Sandbox Code Playgroud)
像这样的事情应该做你想做的:
for cmd in cat head tail; do
cmdLoc=$(type $cmd | awk '{print $3}')
eval "
$cmd() {
for fn in \"\$@\"; do
source-highlight --failsafe --out-format=esc -o STDOUT -i \"\$fn\" |
$cmdLoc -
done
}
"
done
Run Code Online (Sandbox Code Playgroud)
你可以像这样压缩它:
for cmd in cat head tail; do
cmdLoc=$(type $cmd |& awk '{print $3}')
eval "$cmd() { for fn in \"\$@\"; do source-highlight --failsafe --out-format=esc -o STDOUT -i \"\$fn\" | $cmdLoc - ; done }"
done
Run Code Online (Sandbox Code Playgroud)
将以上内容放在 shell 脚本中,称为tst_ccmds.bash
.
#!/bin/bash
for cmd in cat head tail; do
cmdLoc=$(type $cmd |& awk '{print $3}')
eval "$cmd() { for fn in \"\$@\"; do source-highlight --failsafe --out-format=esc -o STDOUT -i \"\$fn\" | $cmdLoc - ; done }"
done
type cat
type head
type tail
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到了您所要求的功能设置:
$ ./tst_ccmds.bash
cat ()
{
for fn in "$@";
do
source-highlight --failsafe --out-format=esc -o STDOUT -i "$fn" 2> /dev/null | /bin/cat - ;
done
}
head is a function
head ()
{
for fn in "$@";
do
source-highlight --failsafe --out-format=esc -o STDOUT -i "$fn" 2> /dev/null | /usr/bin/head - ;
done
}
tail is a function
tail ()
{
for fn in "$@";
do
source-highlight --failsafe --out-format=esc -o STDOUT -i "$fn" 2> /dev/null | /usr/bin/tail -;
done
}
Run Code Online (Sandbox Code Playgroud)
当我在 shell ( source ./tst_ccmds.bash
) 中使用这些函数时,它们的工作原理如下:
猫
头
尾巴
纯文本
最大的技巧(我更愿意称其为 hack)是使用破折号 ( -
) 作为cat
、head
、 和tail
通过管道的参数,这迫使它们输出来自source-highlight
管道 STDIN 的内容。这一点:
...STDOUT -i "$fn" | /usr/bin/head - ....
Run Code Online (Sandbox Code Playgroud)
另一个技巧是使用--failsafe
以下选项source-highlight
:
--failsafe
if no language definition is found for the input, it is simply
copied to the output
Run Code Online (Sandbox Code Playgroud)
这意味着,如果找不到语言定义,它的作用就像cat
简单地将其输入复制到标准输出。
head
如果、tail
或中的任何一个是别名,则该函数将失败cat
,因为调用的结果type
不会指向可执行文件。如果您需要将此函数与别名一起使用(例如,如果您想使用less
需要标志-R
来着色),则必须删除别名并单独添加别名命令:
less(){
for fn in "$@"; do
source-highlight --failsafe --out-format=esc -o STDOUT -i "$fn" |
/usr/bin/less -R || /usr/bin/less -R "$fn"; done
}
Run Code Online (Sandbox Code Playgroud)