Re: bash command substitution, functions and quoting : need help



amwyll.codydd@xxxxxxxxx wrote:

Well, yes, I WANT func() to be executed every time!

Ok. It would be nice of you provided some examples of what you're trying to
do.

But what you probably want is to have all the programs invoked by func()
executed each time, rather than func() itself.

Suppose you want to insert into the prompt the output of two different
external commands (these are only examples, of course): "date +%T"
and "cat /proc/loadavg". The output of "date +%T" should be in blue, the
output of "cat /proc/loadavg" in green.

func() {
BLUE='\[\033[1;34m\]'
GREEN='\[\033[01;32m\]'
NORMAL='\[\033[0m\]'
printf "%s\n" "$BLUE\$(date +%T) $GREEN\$(cat /proc/loadavg) >$NORMAL"
}

If you do

PS1=$(func)

PS1 contains the escape sequences with embedded commands, and both commands
are executed at each prompt. Is this acceptable for you? If not, provide
some example.

thing: just a raw string assigned to PS1. Bash does not re-evaluate the
escape characters.

Could you please elaborate on that particular point? I somehow assumed
that bash re-evaluates escape sequences every time it consults PS1
before outputting the prompt.

No, whatever is output by the function is taken as a string. You don't even
need to take into account escape characters to see that. Try this:

func () {
printf "%s\n" '$(date) > '
}

$ PS1=$(func)
Sun Apr 6 11:56:59 CEST 2008 > # <----- the new prompt
Sun Apr 6 11:57:02 CEST 2008 > echo "$PS1"
$(date) # <----- the value of PS1

Here, bash executes "date" each time and places the output in the prompt,
just as we want. Now do the following:

Sun Apr 6 11:57:07 CEST 2008 > PS1='$(func)'
$(date) > # <----- this is the prompt: a literal string "$(date) > "
$(date) >
$(date) > echo "$PS1"
$(func) # <----- the value of PS1 is $(func), not $(date)
$(date) >

Now, once bash evaluates PS1 and executes func(), the ouput ("$(date)")is
put verbatim in the prompt.

and "\[" ideas. :) Unfortunately, it doesn't seem to answer the
question I have, which is why do SOME escape sequences go awry if
they're output from a function, namely "\[" and "\]" cease being
recognized as "special" escape sequences, but color escape sequences
work out fine... :(

Try the above methods and see if they are appropriate for you; otherwise,
provide specific examples.

Regards

--
All the commands are tested with bash and GNU tools, so they may use
nonstandard features. I try to mention when something is nonstandard (if
I'm aware of that), but I may miss something. Corrections are welcome.
.


Quantcast