我在学校收到了一个作业,如果指定的话,我想生成随机颜色的输出。My program doesn't generate the color that I would like it to when the RANDOM option is selected.
我对该程序的输入是:
echoc RANDOM|colour string
我的代码看起来像:
declare -A colours=(
[black]="0;30" [red]="0;31" [green]="0;32" [yellow]="0;33" [blue]="0;34" [magenta]="0;35" [cyan]="0;36" [white]="0;37"
[BLACK]="1;30" [RED]="1;31" [GREEN]="1;32" [YELLOW]="1;33" [BLUE]="1;34" [MAGENTA]="1;35" [CYAN]="1;36" [WHITE]="1;37")
if [ $# -lt 2 ]; then
echo "Usage: echoc COLOUR|RANDOM STRING"
exit 1
fi
regex='^red$|^green$|^yellow$|^blue$|^magenta$|^cyan$|^white|^black$'
shopt -s nocasematch
if [[ $1 =~ $regex ]]; then
printf '\033[%sm' ${colours[$1]}
shift
printf '%s\033[0m\n' "$*"
exit 0
elif [[ $1 == "RANDOM" ]]; then
printf '\033[%sm' ${colours[$((RANDOM%8+1))]}
shift
printf '%s\033[0m\n' "$*"
exit 3
else
echo COLOUR must be one of 'red|green|yellow|blue|magenta|cyan|white|RANDOM'
exit 2
fi