Sunday, April 28, 2024
30
rated 0 times [  30] [ 0]  / answers: 1 / hits: 73522  / 2 Years ago, wed, march 30, 2022, 2:22:49

If I run echo -e "e[1;31mThis is red texte[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 texte[0m"


run $ sh test.sh



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



Why they act differntly?


More From » command-line

 Answers
4

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 texte[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
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 text033[0m
"

[#26520] Thursday, March 31, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
laceanz

Total Points: 86
Total Questions: 113
Total Answers: 104

Location: Australia
Member since Thu, Jan 26, 2023
1 Year ago
;