2

I was not able to find an answer to this question, so maybe one of you guys can help me out :)

I wrote some shell scripts to help me automate things, and they work. However, what doesn't work is adding colored text to my echos. It works when entering the command directly into my terminal, but it does NOT work when I put the command into a *.sh file:

The Problem

Content of foo.sh:

echo "\n\e[1;37mHello World\e[0m\n"

Can anyone explain to me what the problem is? Oh, and I am using zsh, if that matters.

Thanks a lot in advance :)

Update

Apparently, it works when the content of foo.sh is:

echo $'\n\e[1;37mHello World\e[0m\n'

I found the answer at http://wiki.bash-hackers.org/syntax/quoting, which I found thanks to the answer of netmonk. Therefore, I will accept his answer as the correct one. Thanks mate :)

3
  • what is the result of echo "a\eb" | od -c 1. when type in terminal, 2. when run in zsh ?
    – Archemar
    Oct 9, 2015 at 9:14
  • That'd be "0000000 a 033 b \n 0000004". Why are you asking? I'm curious. My question has been answered, though. Thanks a lot for your effort, it's appreciated :) Oct 9, 2015 at 9:19
  • 1
    I was not sure about escape char ( \e ) being properly used.
    – Archemar
    Oct 9, 2015 at 10:32

2 Answers 2

3

When you save the sh file you probably prepended everything with the "shell" declaration line, like this:

#!/bin/sh

# the code

If you want to achieve same results as when you testing it in your shell change this line to one representing your shell.

1
  • 2
    The shebang line only matters, if the script is made executable and run as command (./foo.sh). If the script is passed as argument to a shell (sh ./foo.sh) - which is what the OP posted - the shebang line will be ignored and the script will be run by that shell.
    – Adaephon
    Oct 15, 2015 at 9:10
1

Yes it matters! The echo command can be different things. A builtin command inside a shell program, or a separate and standalone command.

This way, you can consider that the echo you use inside zsh is not the same that you call in your SH shell script ! :)

you should add -e to you echo inside your script!

2
  • 1
    Note: -e doesn't seem to be necessary, it also works without it Oct 9, 2015 at 9:23
  • 1
    I don't understand how it can work, as far as it didn't worked at first attempt on your side !
    – netmonk
    Oct 9, 2015 at 9:25

You must log in to answer this question.

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