gpt4 book ai didi

bash - 如何显示 bash 支持的所有颜色?

转载 作者:行者123 更新时间:2023-12-02 07:45:38 30 4
gpt4 key购买 nike

有一天,我输入了命令

echo "\033[32mHELLOBASE\033[m"

在 gnome bash shell 中。终端向我显示了一个绿色的 HELLOBASH 字符串。我发现这很有趣。根据我的经验和几次测试,我可以改变数字 32 从 0 到 47。接下来我写了以下代码,

for i in {0..48};do
echo \033[$imHELLOBASH\[033m
done

当然不行,否则我不能在这里!那么如何改进上面的代码功能呢?

最佳答案

让我们以正确的方式来做这件事——使用 tput termcap(或者,对于现代系统,terminfo)数据库中查找颜色代码命令:

for ((i=0; i<=48; i++)); do
tput setaf "$i"
echo HELLOBASH
done

如果您想在 256 色终端上查看所有可用颜色,请使用 BashFAQ #37 中的此代码标记:

colors256() {
local c i j

printf "Standard 16 colors\n"
for ((c = 0; c < 17; c++)); do
printf "|%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n\n"

printf "Colors 16 to 231 for 256 colors\n"
for ((c = 16, i = j = 0; c < 232; c++, i++)); do
printf "|"
((i > 5 && (i = 0, ++j))) && printf " |"
((j > 5 && (j = 0, 1))) && printf "\b \n|"
printf "%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n\n"

printf "Greyscale 232 to 255 for 256 colors\n"
for ((; c < 256; c++)); do
printf "|%s%3d%s" "$(tput setaf "$c")" "$c" "$(tput sgr0)"
done
printf "|\n"
}
colors256

如需了解更多背景信息,请参阅 the bash-hackers page on terminal codes .


顺便说一句,至于为什么您的原始代码即使在使用 ANSI 颜色代码的终端上也无法正常工作——@rici 正确地指出了这一点:您的参数扩展在没有添加大括号的情况下是模棱两可的。

也就是说:

$imHELLOBASH

...需要...

${i}mHELLOBASH

...避免 shell 尝试查找和扩展名为 imHELLOBASH 的变量,而不是名为 i 的变量。

关于bash - 如何显示 bash 支持的所有颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577923/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com