Search code examples
bashprompttput

Select random value from array before every prompt in bash


I'm trying to make a custom prompt that selects one random value from the following lists:

color=(1 2 3 4 5 6)
much=(such very much many so)
wow=(wow hacker terminal geek confusion)

then does this before every prompt.

tput setaf $rcolor
echo -n "$rmuch $rwow $ "

The problem is, if I use PS1, it executes on terminal startup and doesn't update before every prompt. How do I get a different, random message before every prompt?

Sample output:

such hacker $
much wow $
very geek $
such wow $
much confusion $
very terminal $

Solution

  • You have to escape the $:

    PS1="\$(tput setaf \${color[\$RANDOM%6]})\${much[\$RANDOM%5]} \${wow[\$RANDOM%5]}: "
    

    PS1 is evaluated every time is printed.