0

I have some issues with color. It works fine on one line but not on the other 2

 echo "  \e[35mWeather.......:\e[0m `echo "\e[36m$weather\e[0m" | head -1`"
    echo "  \e[35mToday.........:\e[0m `echo "\e[36m$weather\e[0m" | head -2 | tail -1`"
    echo "  \e[35mTomorrow......:\e[0m `echo "\e[36m$weather\e[0m" | tail -1`"

enter image description here

harrymc
  • 455,459
  • 31
  • 526
  • 924
sbh7600
  • 35
  • 5
  • The code is awful. Please read [this](https://unix.stackexchange.com/q/65803/108618), [this](https://unix.stackexchange.com/q/5778/108618) and [this](https://superuser.com/q/1352850/432690). Use `sed $'…' <<< "$weather"` where you make `$'…'` responsible for expanding `\e` and such. E.g. `sed $'s/$/\e[0m/; s/^/ \e[36m/; 1 s/^/ \e[35mWeather.......:/; 2 s/^/ \e[35mToday.........:/; 3 s/^/ \e[35mTomorrow......:/' <<< "$weather"`. – Kamil Maciorowski Dec 04 '19 at 19:31
  • Oh, if there can be more than 3 lines then you need `3 q` at the end: `sed $'s/$/\e[0m/; s/^/ \e[36m/; 1 s/^/ \e[35mWeather.......:/; 2 s/^/ \e[35mToday.........:/; 3 s/^/ \e[35mTomorrow......:/; 3 q' <<< "$weather"` – Kamil Maciorowski Dec 04 '19 at 19:42
  • In addition, please see the *nix command `tput`. Using escape sequences directly is not the way of the Jedi since like 1998. It's POSIX, cleaner, and keeps things compatible with whatever terminal that ends up getting used. – Señor CMasMas Dec 04 '19 at 20:46

1 Answers1

2

Go through your own code step by step.

When you have a multi-line variable and you do this:

"\e[36m$weather\e[0m"

it adds \e[36m to the beginning of the whole variable. It doesn't add the code to the beginning of each and every line in that variable; just to the first line. So the output is something like this:

\e[36mCurrently in Struer, DK: 8 °C and Cloudy
High: 9 C Low: 7 C Mostly cloudy
High: 8 C Low: 8 C Cloudy, a shower; windy\e[0m

So when you take only the 2nd or 3rd line, they do not come with the color code, because there was nothing that would it there. To make it work the way you want, swap the operations – first extract the line you want, then add color codes to the result:

echo "  \e[35mToday.........:\e[0m \e[36m$(echo "$weather" | head -2 | tail -1)\e[0m"
u1686_grawity
  • 426,297
  • 64
  • 894
  • 966