0

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".

6
  • Does /usr/local/bin/bash exists? Commented Jan 31, 2022 at 10:46
  • But why use sh if you want to run with with bash Commented Jan 31, 2022 at 10:46
  • 1
    Not sure where you'd find that escape sequence, but use #!/bin/bash as shebang, then use echo -e '\033[0;31mError: Some Error.\033[0m' and call it with ./script.sh Commented Jan 31, 2022 at 10:56
  • 1
    Side note: if adding colour and other terminal control sequences to a shell script, it's good practise to only do it if the output file descriptor actually refers to a terminal. This allows the sequences to be excluded when piping to a filter, or capturing to a file. You can test if output is to a terminal: test -t 2 for stderr. I like to implement this by using variables for the control sequences (like red_2='\e[41m'), and then only set them if the test returns true for that fd. Commented Jan 31, 2022 at 11:53
  • 1
    Different versions of echo behave differently when parsing options and/or escape sequences; I had a bunch of my scripts break when Mac OS X 10.5 (I think that was the version) came out and its bash built-in changed behavior(!). printf is more complex to use properly (its first argument is a format string that's used to control how the rest of the arguments are printed), but it's way more predictable. For this, I'd use printf '\e[41m%s\e[0m' "Error: Some error.". See this and this. Commented Jan 31, 2022 at 17:43

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.