0x6773
0x6773

Reputation: 1116

Getting value from function, use that value to get colored output in shell

(Using zsh) I am just trying to get random color output whenever I open a new tab in my terminal. To achieve this I wrote the following shell script, but it is not working as expected:

#Standard Colors
red='\033[0;31m'
NC='\033[0m' # No Color
black='\033[0;30m'
blue='\033[0;34m'
green='\033[0;32m'
cyan='\033[0;36m'
purple='\033[0;35m'
yellow='\033[1;33m'
lgreen='\033[1;32m'
lblue='\033[1;34m'
lred='\033[1;31m'
lcyan='\033[1;36m'
#Array color
colr=(red blue green cyan purple yellow lgreen lblue lred lcyan)

#Get random number for colors
randcolr()
{
  sz=${#colr[@]}
  randval=$(( ( RANDOM % sz )  + 1 ))
  echo "${colr[randval]}"
}

echo -e "$(randcolr)TESTING"

Instead of getting colored output, it wrote the name of color and "TESTING" e.g. lgreenTESTING. Any help?(I am using zsh)

The function randcolr always gives same value inside a terminal.

Upvotes: 0

Views: 72

Answers (1)

Josh Jolly
Josh Jolly

Reputation: 11786

When you define your array, you are using strings instead of variables:

colr=(red blue green cyan purple yellow lgreen lblue lred lcyan)

Should be:

colr=($red $blue $green $cyan $purple $yellow $lgreen $lblue $lred $lcyan)

Upvotes: 2

Related Questions