我正在写一个Bash脚本,打印一些文本到屏幕上:

echo "Some Text"

我可以设置文本格式吗?我想把它加粗。


理论上是这样的:

# BOLD
$ echo -e "\033[1mThis is a BOLD line\033[0m"
This is a BOLD line

# Using tput
tput bold 
echo "This" #BOLD
tput sgr0 #Reset text attributes to normal without clear.
echo "This" #NORMAL

# UNDERLINE
$ echo -e "\033[4mThis is a underlined line.\033[0m"
This is a underlined line. 

但实际上,它可能被解释为“高强度”的颜色。

(来源:http://unstableme.blogspot.com/2008/01/ansi-escape-sequences-for-writing-text.html)

我假设bash运行在与vt100兼容的终端上,其中用户没有显式地关闭对格式化的支持。

首先,使用-e选项开启对echo中特殊字符的支持。稍后,使用ansi转义序列ESC[1m],如下所示:

echo -e "\033[1mSome Text"

更多关于ansi转义序列的例子,请访问:ascii-table.com/ansi-escape-sequences-vt-100.php

最兼容的方法是使用tput来发现要发送到终端的正确序列:

bold=$(tput bold)
normal=$(tput sgr0)

然后你可以使用变量$bold和$normal来格式化东西:

echo "this is ${bold}bold${normal} but this isn't"

给了

这个很大胆,但这个不是

为了在字符串上应用样式,你可以使用如下命令:

echo -e '\033[1mYOUR_STRING\033[0m'

解释:

echo -e -e选项表示将解释转义(反斜杠)的字符串 \033转义序列表示样式的开始/结束 小写的m -表示序列的结束 1 -粗体属性(详见下文) [0m -重置所有属性,颜色,格式等

可能的整数为:

0 -普通样式 1 -大胆 2 -昏暗 3 -斜体 4 -划线 5 -眨眼 7 -反向 8 .隐形

这是一篇旧文章,但无论如何,你也可以通过使用utf-32来获得黑体和斜体字符。甚至还有希腊语和数学符号可以像罗马字母一样使用。