the*_*fog 10 colors bash escape-characters
我正在用 Bash 脚本打印一条消息,我想对其中的一部分进行着色;例如,
#!/bin/bash
normal='\e[0m'
yellow='\e[33m'
cat <<- EOF
${yellow}Warning:${normal} This script repo is currently located in:
[ more messages... ]
EOF
Run Code Online (Sandbox Code Playgroud)
但是当我在终端(tmux内部gnome-terminal)中运行时,ANSI 转义字符只是以\形式打印;例如,
\e[33mWarning\e[0m This scr....
Run Code Online (Sandbox Code Playgroud)
如果我将想要着色的部分移动到printfhere-doc 之外的命令中,它会起作用。?例如,这有效:
printf "${yellow}Warning:${normal}"
cat <<- EOF
This script repo is currently located in:
[ more messages... ]
EOF
Run Code Online (Sandbox Code Playgroud)
从man bash- 这里文件:
不会对word执行参数和变量扩展、命令替换、算术扩展或路径名扩展。如果word中的任何字符被引用,则分隔符是word上引用删除的结果,并且 here-document 中的行不会被扩展。如果word 没有被引用,here-document 的所有行都会进行参数扩展、命令替换和算术扩展。在后一种情况下,字符序列\ <换行符>被忽略,
\必须使用来引用字符\,$和`。
我无法弄清楚这将如何影响 ANSI 转义码。是否可以在 Bash here 文档中使用 ANSI 转义码cat?
Tho*_*key 28
在您的脚本中,这些分配
normal='\e[0m'
yellow='\e[33m'
Run Code Online (Sandbox Code Playgroud)
将这些字符按字面意思放入变量中,即\e[0m,而不是转义序列。您可以使用printf(或某些版本echo)构造转义字符,例如,
normal=$(printf '\033[0m')
yellow=$(printf '\033[33m')
Run Code Online (Sandbox Code Playgroud)
但是你会做得更好tput,因为这适用于任何正确设置的终端:
normal=$(tput sgr0)
yellow=$(tput setaf 3)
Run Code Online (Sandbox Code Playgroud)
查看您的示例,似乎printf您使用的版本将\e视为转义字符(这可能适用于您的系统,但通常不能移植到其他系统)。要查看此内容,请尝试
yellow='\e[33m'
printf 'Yellow:%s\n' $yellow
Run Code Online (Sandbox Code Playgroud)
你会看到文字字符:
Yellow:\e[33m
Run Code Online (Sandbox Code Playgroud)
而不是转义序列。将这些放在printf格式中告诉printf解释它们(如果可以的话)。
进一步阅读:
| 归档时间: |
|
| 查看次数: |
7784 次 |
| 最近记录: |