Home > Enterprise >  Color code in Bash using for loop in a Linux terminal
Color code in Bash using for loop in a Linux terminal

Time:09-25

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:

CodePudding user response:

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

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

CodePudding user response:

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

CodePudding user response:

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}"
  • Related