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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

here is my function to print color text:

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"

$ 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
Take a look at: mywiki.wooledge.org/BashFAQ/037?highlight=%28color%29 – val0x00ff Apr 30 '14 at 14:33
Be aware that the string you are proposing might be $term specific thus the answer here is not necessarily universal. – mdpc Apr 30 '14 at 18:02

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 '14 at 17:13
This solution print in black '-n ' at the left of the text I want to print coloured. – user1850133 Apr 30 '14 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 '14 at 20:25

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


colorreset=$(tput sgr0)    #  back to black after function return
while read line; do
 if [[ ! -n $color  ]]; then
  printf '%s\n' "$line $colorreset"
  printf '%s\n' "$1$line $colorreset" 
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 '14 at 20:23

Your Answer


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.