You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否使用tput实现终端文本属性的压入/弹出操作?

解决tput局部加粗不影响原有颜色的问题

精准取消加粗(推荐方案)

tput支持通过sgr命令指定具体的ANSI SGR控制参数,其中22是标准的「取消加粗/浅淡样式」指令,只会关闭加粗效果,不会影响之前设置的颜色等其他属性:

echo "$(tput setaf 1)this is red; $(tput bold)this is bold; $(tput sgr 22)this is red, but not bold"

这个方案兼容性强,几乎所有支持ANSI序列的终端都能正常工作。

重置后恢复颜色(兼容极端场景)

如果某些终端不支持sgr 22,可以用「重置所有属性+重新设置颜色」的兜底方案,虽然步骤多一点,但能保证在所有终端生效:

echo "$(tput setaf 1)this is red; $(tput bold)this is bold; $(tput sgr0; tput setaf 1)this is red, but not bold"

属性压入/弹出(仅限部分终端)

部分现代终端(如xterm、Konsole)支持属性的保存与恢复,对应的tput命令为save和restore,可以实现你想要的「压入-修改-弹出」逻辑:

echo "$(tput setaf 1)this is red; $(tput save; tput bold)this is bold; $(tput restore)this is red, but not bold"

但要注意,这个功能不是ANSI标准,老旧终端或简化终端可能不支持,所以仅作为备选方案。

内容的提问来源于stack exchange,提问作者Roger Lipscombe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:00:07