ANSI转义代码,用于在bash printf中着色 [英] ANSI escape codes for coloring inside bash printf
本文介绍了ANSI转义代码,用于在bash printf中着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的8.
和9.
行使我感到困惑:
Lines 8.
and 9.
below confound me:
#!/bin/bash
a=foo
b=6
c=a
d="\e[33m" # opening ansi color code for yellow text
e="\e[0m" # ending ansi code
f=$d
printf "1. foo\n"
printf "2. $a\n"
printf "3. %s\n" "$a"
printf "4. %s\n" "${!c}"
printf "5. %${b}s\n" "$a"
printf "6. $d%s$e\n" "$a" # will be yellow
printf "7. $f%s$e\n" "$a" # will be yellow
printf '8. %s%s%s\n' "$d" "$a" "$e" # :(
printf "9. %s%s%s\n" "$f" "$a" "$e" # :(
是否可以使用%s
扩展颜色变量并查看颜色开关?
Is it possible to use %s
to expand a colour variable and see the colour switch?
输出:
1. foo
2. foo
3. foo
4. foo
5. foo
6. foo
7. foo
8. \e[33mfoo\e[0m
9. \e[33mfoo\e[0m
注意:6.
和7.
确实是黄色
printf "10. %b%s%b\n" "$f" "$a" "$e" # :)
...终于!这是执行此命令的命令,这要感谢Josh!
... finally! That's the command that does it, thanks to Josh!
推荐答案
您正在寻找一种格式说明符,该说明符将扩展参数中的转义符.方便地,bash支持(来自help printf
):
You're looking for a format specifier that will expand escape characters in the argument. Conveniently, bash supports (from help printf
):
%b expand backslash escape sequences in the corresponding argument
或者,bash还支持一种特殊的机制,通过该机制可以执行转义符的扩展:
Alternatively, bash also supports a special mechanism by which will perform expansion of escape characters:
d=$'\e[33m'
这篇关于ANSI转义代码,用于在bash printf中着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文