2

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

2 Answers 2

3

Short answer: you can't, bash doesn't have the equivalent of pointers. The variable $TITLE is assigned with the expansion of the rhs of the assignment character, so $TITLE has the value %s\e[m since $FG is not defined at expansion time, and hence expands to the empty string. As a work-around you could instead do:

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"
}

And using eval is not really a good option, as eval is evil!

I've also modified a few things from your script:

  • 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.

1
  • your solution works fine, but is necesary the extra parameter $FG for each printf command. how aboid this?
    – rkmax
    Nov 30, 2012 at 16:59
1

TITLE is expanded to include ${FG} where you type it, not when you use it. one solution is to:

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

then

eval printf "$TITLE" "One"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.