1
$ echo -e "test1\ntest2" > logfile

$ echo -e "test1\ntest2" >> logfile

$ cat logfile
test1
test2
test1
test2

$ rm logfile

$ crontab -e
* * * * * echo -e "test1\ntest2" >> logfile

$ sleep 160

$ cat logfile
-e test1
test2
-e test1
test2

Why am I getting the -e in the output? Both crontab and bash are using /bin/echo

aidan
  • 615
  • 4
  • 10
  • 23

2 Answers2

9

They're probably not both using /bin/echo. The environment used by cron is probably different from your interactive environment. Specify the full path to be sure.

medina
  • 1,970
  • 10
  • 7
  • well, before I tried this test, I tried another test: `* * * * * which echo > logfile` -- it showed the same thing as `which echo` – aidan Aug 12 '10 at 10:13
  • ...but specifying the full path as you suggest does fix the problem. Strange?! – aidan Aug 12 '10 at 10:17
  • 1
    aidan: "which" doesn't search for shell built-ins, it looks for files under $PATH. That's why "which echo" shows identical results, and that's why the interactive environment and cron can differ. – Janne Pikkarainen Aug 12 '10 at 10:49
  • 1
    Golden rule of crons: Always use full paths. If you always follow the rule, you won't get something unexpected or borken. – labradort Aug 12 '10 at 14:54
  • 2
    `type echo` should provide you some clarity here :) – medina Aug 12 '10 at 19:53
3

This is one of the reasons people recommend using printf instead of echo for portability.

* * * * * printf "test1\ntest2\n" >> logfile

The shell that cron uses is sh rather than Bash. On my system, sh is really Dash and its echo doesn't have -e. So -e becomes just another string to be output. Other versions of the Bourne shell or shells that provide its functionality may have -e.

If you use echo without the full path in your crontab, you're getting the shell's builtin echo instead of /bin/echo. On the command line, if you're using Bash, then echo without the full path gives you Bash's builtin version.

Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148