我有一个全局变量
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
变量
简短的回答:你不能,bash 没有指针的等价物。该变量$TITLE
是通过赋值字符的 rhs 的扩展来赋值的,因此在扩展时未定义$TITLE
值%s\e[m
since ,因此扩展为空字符串。$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
邪恶也是如此!
我还从您的脚本中修改了一些内容:
$'...'
to have the correct colors (instead of the strings "\e[m"
, ...),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.
TITLE 被扩展为包括${FG}
您键入它的位置,而不是您使用它的时间。一种解决方案是:
TITLE='${FG}%s${RT}'
然后
eval printf "$TITLE" "One"