16

If I run echo -e "\e[1;31mThis is red text\e[0m" in comand line, It prints out red text.

However, if I use write it in script file test.sh

#! /bin/bash
echo -e "\e[1;31mThis is red text\e[0m"

run $ sh test.sh

It prints out -e \e[1;31mThis is red text\e[0m

Why they act differntly?

3 Answers 3

30

echo is a shell builtin in Bash and dash (/bin/sh). If you run echo from the command line you are using the Bash builtin, if you are running your shell script with sh you are using the Dash builtin.

The dash version of echo doesn't know the -e option but just outputs anything verbatim without any special handling for \ sequences.

Either use Bash to run your shell script, or use /bin/echo instead of echo:

/bin/echo -e "\e[1;31mThis is red text\e[0m"

To avoid the problems with different versions of echo you may want to use printf instead. In contrast to echo printf always interprets \ sequences but doesn't automatically add a linefeed at the end so you have to append \n at the end if you want one.

As some versions of printf don't understand \e you should use \033 instead:

printf "\033[1;31mThis is red text\033[0m\n"
1
  • It works. /bin/echo with dash(/bin/sh) and bash; echo with bash or ./tes.sh both works correctly. Code below works with bash only. if [ $UID -ne 0 ]; then echo "Not root user" else echo "Root User" fi
    – qingfeng
    Mar 14, 2014 at 12:30
3

This needs the correct command in the correct format is all.

Proper echo statement: echo "Hello World!"

Proper echo statement with color: echo "\e[1;31mHello World!\e[0m"

Adding color to a bash script is one of those very simple but easily confusing things. =)

This site could help explain it all clearly to you. I often use it as reference because, who can remember all the correct color codes right? LOL

1

Don't run it with sh test.sh, it prints the text in white colour like you said..After creating the script, make it executable by running,

sudo chmod +x /path/test.sh

enter image description here

Run the script with sudo,like sudo ./test.sh or ./test.sh both will works.

Or

Run the script with bash,

bash /path/test.sh
4
  • I run chmod a+x test.sh, it print the text in read color. What is the difference. ./test.sh should be equal to sh test.sh What happened in linux?
    – qingfeng
    Mar 14, 2014 at 12:14
  • you don't had to use sh while running the script, you have created the script with bash interpreter #! /bin/bash so you have to use bash test.sh Mar 14, 2014 at 12:15
  • And also . means current directory. Mar 14, 2014 at 12:16
  • See the screenshot, my test.sh file is placed inside the desktop.So i moved to that desktop folder and then i run ./test.sh ,finally it works.Please keep in mind run the script with . only if it was presented inside the current directory. Mar 14, 2014 at 12:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .