GauravSolo
GauravSolo

Reputation: 71

Color code in Bash using for loop in a Linux terminal

When I use color code separately in the echo statement, it works fine.

But I am trying to write 5 colored statements using for loop but it is not working.

What can I do?

#!/bin/bash

for i in {31..35}
do
    echo -e "Normal \e[$imColoredText  \e[0m"
done

Output of individual code:

Output of Bash script:

Upvotes: 0

Views: 726

Answers (3)

William Pursell
William Pursell

Reputation: 212424

echo and printf are both too fragile:

for i in {1..5}; do 
    echo Normal; tput setaf $i; echo ColoredText; tput setaf 9;
done

You can also do things like:

for i in {1..5}; do printf "Normal%sColoredText%s\n" "$(tput setaf $i)" "$(tput setaf 9)"; done

or:

red=$(tput setaf 1)
normal=$(tput setaf 9)
echo "${normal}Normal${red}Red${normal}"

Upvotes: 1

Léa Gris
Léa Gris

Reputation: 19615

It is preferable not to use echo -e which is non-standard, but prefer printf instead.

Here it is:

#!/usr/bin/env sh

i=1
while [ $i -le 5 ]; do
  printf 'Normal '
  tput setaf "$i"
  printf 'ColoredText'
  tput sgr0
  printf '\n'
  i=$((i + 1))
done

Upvotes: 1

Alireza
Alireza

Reputation: 2123

You need to put your loop variable in curly brackets (variable expansion):

echo -e "Normal \e[${i}mColoredText \e[0m"

Upvotes: 0

Related Questions