首页 文章

用于在bash printf内着色的ANSI转义码

提问于
浏览
6

下面的行 8.9. 混淆了我:

#!/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 扩展颜色变量并查看颜色开关?

输出:

1. foo
2. foo
3. foo
4. foo
5.    foo
6. foo
7. foo
8. \e[33mfoo\e[0m
9. \e[33mfoo\e[0m

Note6.7. 确实是黄色的


编辑

printf "10. %b%s%b\n" "$f" "$a" "$e" # :)

......终于来了!这就是它的命令,感谢Josh!

1 回答

  • 10

    您正在寻找一个格式说明符,它将在参数中展开转义字符 . 方便地,bash支持(来自 help printf ):

    %b        expand backslash escape sequences in the corresponding argument
    

    或者,bash还支持一种特殊的机制,通过它可以执行转义字符的扩展:

    d=$'\e[33m'
    

相关问题