Select bash 中每个提示之前数组中的随机值

Select random value from array before every prompt in bash

我正在尝试制作一个自定义提示,从以下列表中选择一个随机值:

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

然后在每次提示之前执行此操作。

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

问题是,如果我使用 PS1,它会在终端启动时执行,并且不会在每次提示之前更新。 如何在每次提示前获得不同的随机消息?

示例输出:

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

你必须逃避 $:

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

PS1 每次打印都会被计算。

您也可以使用 trap

much=(such very much many so)
wow=(wow hacker terminal geek confusion)
max=${#much[@]}
trap 'PS1="${much[$((RANDOM % max))]} ${wow[$((RANDOM % max))]} $ "' DEBUG

输出:

much confusion $
such terminal $
such confusion $
such geek $
so terminal $
very confusion $
such geek $
such terminal $
much terminal $
many geek $