echo 命令颜色不起作用
echo command color not working
我有这样的代码:
#!/bin/bash
COLOR_REST='\e[0m'
COLOR_GREEN='\e[0;32m'
echo -e "${COLOR_GREEN}OK${COLOR_REST}"
当我将代码复制并粘贴到我的 iTerm 中时,它以绿色显示 OK
。
但是,当我将代码存储在名为 testColor.sh
的文件中并执行 ./testColor.sh
时。它在我的屏幕上显示 \e[0;32mOK\e[0m
。
为什么 OK
不显示为绿色?
我也试过 bash testColor.sh
和 sh testColor.sh
。两者都无法以绿色显示文本。
另外一个我觉得奇怪的是在man echo
.
中的BSD通用命令手册中没有看到-e
选项
我正在使用 macOS High Sierra 作为我的操作系统。
使用 printf
而不是 echo
应该适用于任何 POSIX 兼容的 shell。我在 High Sierra 中使用默认终端尝试了这个,但它没有用(没有任何扩展选项,只有 -n
)。
至于解释,我没有使用过 iTerm,所以我不完全确定,但可能是 iTerm 的不同 echo
实现,这会导致标志仅在使用 iTerm 本身时起作用,而不是 /bin/bash。请注意,在 echo
的手册页中,它说
NOTE: your shell may have its own version of echo, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports.
使用
#!/bin/bash
COLOR_REST="$(tput sgr0)"
COLOR_GREEN="$(tput setaf 2)"
printf '%s%s%s\n' $COLOR_GREEN 'OK' $COLOR_REST
它使用 printf 来避免 echo
选项,并且 tput
可以跨不同的终端移植。
我很喜欢这种语法:
echo $'\e[31mRED\e[0m'
$'...'
表示法使 shell 接受转义码,例如\t
, \n
, \e
.
这似乎适用于 bash、ksh、zsh 和 sh -- 是的,适用于 MacOS。
问题似乎是达尔文的 BSD-era /bin/echo
实际上根本不接受 -e
论点。最近版本的 MacOS 中的 zsh
有一个内置的 echo
确实 采用 -e
,但这显然不能移植到其他 shell s 除非你想 运行 每个 shell 脚本 zsh.
我有这样的代码:
#!/bin/bash
COLOR_REST='\e[0m'
COLOR_GREEN='\e[0;32m'
echo -e "${COLOR_GREEN}OK${COLOR_REST}"
当我将代码复制并粘贴到我的 iTerm 中时,它以绿色显示 OK
。
但是,当我将代码存储在名为 testColor.sh
的文件中并执行 ./testColor.sh
时。它在我的屏幕上显示 \e[0;32mOK\e[0m
。
为什么 OK
不显示为绿色?
我也试过 bash testColor.sh
和 sh testColor.sh
。两者都无法以绿色显示文本。
另外一个我觉得奇怪的是在man echo
.
-e
选项
我正在使用 macOS High Sierra 作为我的操作系统。
使用 printf
而不是 echo
应该适用于任何 POSIX 兼容的 shell。我在 High Sierra 中使用默认终端尝试了这个,但它没有用(没有任何扩展选项,只有 -n
)。
至于解释,我没有使用过 iTerm,所以我不完全确定,但可能是 iTerm 的不同 echo
实现,这会导致标志仅在使用 iTerm 本身时起作用,而不是 /bin/bash。请注意,在 echo
的手册页中,它说
NOTE: your shell may have its own version of echo, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports.
使用
#!/bin/bash
COLOR_REST="$(tput sgr0)"
COLOR_GREEN="$(tput setaf 2)"
printf '%s%s%s\n' $COLOR_GREEN 'OK' $COLOR_REST
它使用 printf 来避免 echo
选项,并且 tput
可以跨不同的终端移植。
我很喜欢这种语法:
echo $'\e[31mRED\e[0m'
$'...'
表示法使 shell 接受转义码,例如\t
, \n
, \e
.
这似乎适用于 bash、ksh、zsh 和 sh -- 是的,适用于 MacOS。
问题似乎是达尔文的 BSD-era /bin/echo
实际上根本不接受 -e
论点。最近版本的 MacOS 中的 zsh
有一个内置的 echo
确实 采用 -e
,但这显然不能移植到其他 shell s 除非你想 运行 每个 shell 脚本 zsh.