0

I have a cron job ...

/bin/sh /usr/local/maint/update-wp-sites 2>&1 > /usr/local/maint/output/update-wp-sites.$(date +"\%F_\%H\%M\%S").txt

It works great.

Here's the code for update-wp-sites:

red='\033[0;31m'
color_off='\033[0m'
echo -e "$red updating wp core $color_off"
wp core update

But the output in the update-wp-sites.$(date ...) file specified above looks like this:

-e updating wp core
Success: WordPress is up to date.

Why is "-e" appearing?

  • Because `echo` may be a builtin command of the shell or an external command and there are different implementations with different command line options. Some versions need `-e` to process escape sequences, others don't. – Bodo Mar 18 '20 at 13:26
  • Why are you using the `-e` option anyways? What is it that you're trying to escape? –  Mar 18 '20 at 13:30
  • 1
    I know it's tempting, and it seems like a good idea to embed terminal codes in your output to get colored output, but don't do it. I guarantee that if the logs are useful, they will find their way into some where that the color codes don't actually change color but just clutter up the output (eg, you'll view them via a browser in kibana), and you'll be cursing the author for including junk in the log. Just write text. – William Pursell Mar 18 '20 at 13:43
  • Thanks William, you're absolutely right. I never use colored output/terminal codes but wanted to play around a little last night only to discover this issue. I already removed them, but was still curious why this output as it did. – Code Prowler Mar 18 '20 at 13:50
  • You are running bash code with sh, so it's behaving differently. See https://stackoverflow.com/questions/15179446/why-does-my-bash-code-fail-when-i-run-it-with-sh – that other guy Mar 18 '20 at 16:07

1 Answers1

1

Use printf (which is Posix standard) instead of the non-standard echo -e:

red='\033[0;31m'
color_off='\033[0m'
printf "${red}%s${color_off}\n" "updating wp core"
wp core update

The same applies to echo -n.

Posix does not specify any command-line options for echo, and a Posix-compliant echo simply prints all of its arguments verbatim, including the ones which look like command-line options.

The common (but not universal) extensions to echo can really get in the way: there is no portable way to use them nor to suppress them (in case you wanted to output something starting with -e, for example).

Better to stick with printf, which is a built-in on most shells, which has standardized behaviour, and which is cleanly extensible.

rici
  • 234,347
  • 28
  • 237
  • 341
  • While I still don't know why -e is appearing, this answer is the right one. I will use printf from now on. Thank you rici. – Code Prowler Mar 18 '20 at 13:51
  • 2
    @code: because the shell used by crontab has a standard `echo` which echos all its arguments verbatim. – rici Mar 18 '20 at 14:00