为什么这个 bash 脚本的函数可以工作?

问题描述 投票:0回答:1

我在教程中看到了一个功能,我认为它非常酷。它用于为文本着色。

函数定义如下:

function print_color(){

  case $1 in
    "green") COLOR='\033[0;32m' ;;
    "red") COLOR='\033[0;31m' ;;
    "*") COLOR='\033[0m' ;;
  esac

  echo -e "${COLOR} $2"

然后就这样称呼:

# Install and configure firewalld
print_color "green" "Installing FirewallD.. "
apt search datadog

然后它会将文本“Installing FirewallD..”着色。

因此该函数仅当您在 $2 之前加上 ${COLOR} 时才起作用。我的问题是,这是如何以及为什么会这样?为什么我需要回显 ${COLOR},以便当我回显 $2 时,它会着色?如果我删除 ${COLOR} 的回显,则着色将不起作用。我想知道是因为我想更深入地了解 BASH。

谢谢。

脚本有效。我想知道为什么它会这样工作。

linux bash function echo variable-assignment
1个回答
0
投票

它们被称为 ANSI 转义码。你可以像这样使用它们(为了简单起见,Python 中的示例代码):

red = "\033[0;31m"
no_color = "\033[0m"
print("Something with normal color " + red + "something with red " + no_color + "something with normal color")

输出“红色的东西”为红色,其他所有内容都为默认颜色。

© www.soinside.com 2019 - 2024. All rights reserved.