2

我有一个全局变量

RT="\e[m"
TITLE="${FG}%s${RT}"

并且有两个功能

function one
{
   local FG="\e[33m"
   printf "$TITLE" "One"
}

function two
{
   local FG="\e[32m"
   printf "$TITLE" "Two"
}

但颜色不改变,如何重用$TITLE变量

4

2 回答 2

3

简短的回答:你不能,bash 没有指针的等价物。该变量$TITLE是通过赋值字符的 rhs 的扩展来赋值的,因此在扩展时未定义$TITLE%s\e[msince ,因此扩展为空字符串。$FG作为一种解决方法,您可以改为:

rt=$'\e[m'
title="%s%s$rt"

one() {
    local fg=$'\e[33m'
    printf "$title" "$fg" "One"
}

two() {
    local fg=$'\e[32m'
    printf "$title" "$fg" "Two"
}

使用eval并不是一个好的选择,eval邪恶也是如此!

我还从您的脚本中修改了一些内容:

  • Used lower case variable names (as using upper case variable names is considered bad practice in bash),
  • Use $'...' to have the correct colors (instead of the strings "\e[m", ...),
  • Used the proper way to define functions in bash (without the keyword function).

Edit. From your comment, I see you're really troubled with having to type "$fg" each time. So here's another possibility: instead of defining a variable $title, define a function title that echos the formating string and use it like so:

rt=$'\e[m'

title() {
   echo "$fg%s$rt"
}

one() {
    local fg=$'\e[33m'
    printf "$(title)" "One"
}

two() {
    local fg=$'\e[32m'
    printf "$(title)" "Two"
}

Each time you call the function title, it echoes the formating string you need, hence $(title) will expand to that formating string. Each time you call the function title, the string "$fg%s$rt" is expanded, with whatever values the variables $fg and $rt have at this expansion time.

于 2012-11-30T16:49:34.577 回答
1

TITLE 被扩展为包括${FG}您键入它的位置,而不是您使用它的时间。一种解决方案是:

TITLE='${FG}%s${RT}'

然后

eval printf "$TITLE" "One"
于 2012-11-30T16:42:17.227 回答