I have a global variable
RT="\e[m"
TITLE="${FG}%s${RT}"
and have two functions
function one
{
local FG="\e[33m"
printf "$TITLE" "One"
}
function two
{
local FG="\e[32m"
printf "$TITLE" "Two"
}
but the color dont change, how to reuse the $TITLE variable
Short answer: you can’t, bash doesn’t have the equivalent of pointers. The variable
$TITLEis assigned with the expansion of the rhs of the assignment character, so$TITLEhas the value%s\e[msince$FGis not defined at expansion time, and hence expands to the empty string. As a work-around you could instead do:And using
evalis not really a good option, asevalis evil!I’ve also modified a few things from your script:
$'...'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 functiontitlethat echos the formating string and use it like so: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 functiontitle, the string"$fg%s$rt"is expanded, with whatever values the variables$fgand$rthave at this expansion time.