gpt4 book ai didi

bash - echo 命令颜色不起作用

转载 作者:行者123 更新时间:2023-11-29 09:36:12 25 4
gpt4 key购买 nike

我有这样的代码:

#!/bin/bash

COLOR_REST='\e[0m'
COLOR_GREEN='\e[0;32m'
echo -e "${COLOR_GREEN}OK${COLOR_REST}"

当我将代码复制并粘贴到我的 iTerm 中时,它以绿色显示 OK

enter image description here

但是,当我将代码存储在名为testColor.sh 的文件中并执行./testColor.sh 时。它在我的屏幕上显示 \e[0;32mOK\e[0m

为什么不显示绿色的OK

我还尝试了 bash testColor.shsh testColor.sh。两者都无法以绿色显示文本。

另外我觉得奇怪的是,在man echo中没有看到BSD General Commands Manual中的-e选项。

我使用 macOS High Sierra 作为我的操作系统。

最佳答案

使用

#!/bin/bash

COLOR_REST="$(tput sgr0)"
COLOR_GREEN="$(tput setaf 2)"
printf '%s%s%s\n' $COLOR_GREEN 'OK' $COLOR_REST

它使用 printf 来避免 echo 选项和 tput 以跨不同终端移植。

关于bash - echo 命令颜色不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49503805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com