Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

here is my function to print color text:

cecho()
{
color=${1:-""}       #  defaults to original color if no color specified
colorreset="\E[0m"   #  back to black after function return
while read line; do
  echo -e "$color$line$colorreset"
done
return
}

$ blue="\E[34m"
$ echo "message" | cecho $blue
$ message  #  it appears in blue

but if I use -n option then nothing is printed:

$ echo -n "message" | cecho $blue
$

I need '-n' option because sometimes I print text with only a word with color in the whole line, like:

$ echo -n "this is "
$ echo "blue" | cecho $blue
share|improve this question
    
    
Be aware that the string you are proposing might be $term specific thus the answer here is not necessarily universal. –  mdpc Apr 30 at 18:02

3 Answers 3

I think you problem is related to the fact that "read" requires an end of line to read the input. Thus it will hang until some kind of input is entered (i.e. for ever).

Perhaps you should add '-n' option to cecho instead, that is.

$ echo "message | cecho -n $blue

then rewrite your function to check for the '-n', and then apply it to the echo inside of cecho.

share|improve this answer
    
To do that simply replace color="${1:-""}" into color="${*:-""}" –  Emmanuel Apr 30 at 17:13
    
This solution print in black '-n ' at the left of the text I want to print coloured. –  user1850133 Apr 30 at 20:27

Michael's answer correctly states that read is not returning anything because there is no newline at the end of the data being read. You can avoid this by altering the while condition like this:

while read line || [ -n "$line" ];
share|improve this answer
    
this solution puts a trailing newline even when I use 'echo -n'. –  user1850133 Apr 30 at 20:25

To achieve what you want, I'd do something as the following:

#!/bin/bash

cecho()
{
color="${1:-""}"
colorreset=$(tput sgr0)    #  back to black after function return
while read line; do
 if [[ ! -n $color  ]]; then
  printf '%s\n' "$line $colorreset"
 else
  printf '%s\n' "$1$line $colorreset" 
fi
done
return
}
cecho "$1"

enter image description here

share|improve this answer
    
what about printing text without the trailing newline? I tried your solution, using the -n option for echo makes the same problem as I had with my code. –  user1850133 Apr 30 at 20:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.