I wanted to have colored ping
command output using a shell script. But in the process, I ended up having my command line also colored. Is there any way I can have only my output colored?
Here is my bash script:
#!/bin/bash num=1 for((i=1; i <= "$1"; i++)) do echo "$(tput setaf "$num")Hello $i" ((num=num + 1)) done
Please see this for example:
Advertisement
Answer
You need to reset the color after you set it. With tput, this can be done using tput sgr0
(which removes all attributes). Example:
#!/bin/bash num=1 for((i=1; i <= "$1"; i++)) do echo "$(tput setaf "$num")Hello $i$(tput sgr0)" ((num=num + 1)) done
Think of the color setting as markup, and your terminal emulator is something which shows the marked up text. It cannot know where program output begins and ends, as all it receives is a continous stream of text (and control codes for “markup”). Depending on your prompt configuration (see echo $PS1
), your prompt may or may not have markup to set the color. If it does not, then there is nothing which overrides the color markup given by the output of your program, thus, the prompt gets whatever color your program last set.
(Note: My bash does not support whatever syntax you are using there for the for-loop condition. I just changed the relevant parts.)