Home > Mobile >  How to write a text color randomizer that doesn't repeat in bash?
How to write a text color randomizer that doesn't repeat in bash?

Time:10-31

I'm trying to write a stupid program that randomizes text color without repeating in bash and I don't know how.

#!/bin/bash
name=$1
number=$2
array1=()
for i in {1..$number}; do
  random=$(($RANDOM % 6   31))
  array1 =($random)
  color="\033[0;${random}m"
  while["${array1[*]}" =~ "${color}"]; do
    random=$(($RANDOM % 6   31))
    array1[$i]="$random"
 done
echo -e $color$name
done

CodePudding user response:

If you want to print name in number different colors, you can use an associative array to ensure each random color is unique

#! /bin/bash

MAX=256

name="$1"
number="$(($2 > MAX ? MAX : $2))"

declare -A colors
while (( ${#colors[@]} < number)); do
    color=$((RANDOM % MAX))
    if [[ ! "${colors[$color] ?}" ]]; then
        colors[$color]=1
        printf '%s%s%s\n' "$(tput setaf ${color})" "${name}" "$(tput sgr0)"
    fi
done

I set the max to 256 but you can use any number. Also, it's using tput instead of hardcoding escape sequences.

  •  Tags:  
  • bash
  • Related