Home > Back-end >  Use echo options when execution shell script
Use echo options when execution shell script

Time:02-01

On mac OSX, I have this script:

#!/usr/local/bin/bash
echo -e "\e[41mError: Some error.\e[0m"

When I just run the echo -e ... in a console, it prints the colored text "Error: Some error."

When executed as a script sh myscript.sh, it litterally prints the flag and the escape characters: -e "\e[41mError: Some error.\e[0m".

When I add the script location to ~/.bash_profile and execute it as myscript.sh, it does work. But I need to be able execute it without adding it to my bash profile.

Edit: using printf works: printf "\e[41mError: Some error.\e[0m\n".

CodePudding user response:

when you run the shell with sh it runs in posix compatibility mode (i.e. as the bourne shell does)

bash is a successor to this shell, one of the features it adds is the -e switch to echo

in posix shell you don't need the -e, the escapes will be evaluated anyway

in bash you do, so if you want to run bash do so explicitly

  •  Tags:  
  • Related