Lin*_*eak 3 colors terminal shell-script portability tput
tput#!/bin/sh
colors_supported()
{
command -v tput > /dev/null 2>&1 && tput setaf 1 > /dev/null 2>&1
}
Run Code Online (Sandbox Code Playgroud)
我目前正在使用此代码来确定是否tput支持终端颜色。
它似乎运行良好,问题是:这段代码是否 POSIX-ly 100% 可移植并可用于各种基于 Unix 的系统?我的意思是 Linux、*BSD 等。
我问是因为我现在不能到处尝试。
哪些颜色:
tput setaf 1
tput setaf 2
tput setaf 3
tput setaf 4
tput setaf 5
tput setaf 6
tput setaf 7
Run Code Online (Sandbox Code Playgroud)
建议的检查将无法在某些 Unix 系统上工作。
POSIX 不涵盖 的这方面tput,但请阅读手册页的可移植性部分。
大多数系统确实使用 terminfo 名称(例如setaf)。
例如,FreeBSD(尽管底层库是ncurses)提供了一个tput只支持termcap名称的。FreeBSD手册页不清楚,但请参阅源代码,它使用tgetstr( termcap) 而不是tigetstr( terminfo)。
该terminfo手册页列出了terminfo和termcap名称,例如,setaf和AF。您可以尝试连续使用两者,因为退出代码会说明是否定义了功能。
例如,您可以修改您的测试函数以通过以下方式处理任一情况:
colors_supported()
{
command -v tput > /dev/null 2>&1 && ( tput setaf || tput AF ) > /dev/null 2>&1
}
Run Code Online (Sandbox Code Playgroud)