1

As per the graylog2 docs, I need to add this line to my rsyslog.conf:

$template GRAYLOGRFC5424,"<%pri%>%protocol-version% %timestamp:::date-rfc3339% %HOSTNAME% %app-name% %procid% %msg% \n"

I'm doing it programmatically when I spin up a server, so the command I've got going currently is:

sudo sh -c 'echo "\$template GRAYLOGRFC5424,\"<%pri%>%protocol-version% %timestamp:::date-rfc3339% %HOSTNAME% %app-name% %procid% %msg% \\\n\"" >> rsyslog.conf'

I'm escaping the dollar sign, both double quotes, and the backslash before the n. However, \n and \\n both write an actual newline to the file, but \\\n writes \n correctly. Why doesn't \\n work?

2
  • 1
    Even though tag bash, the behaviour is with sh. If you do sudo bash -c ..., you'll get different results. – muru Oct 6 '14 at 16:52
  • ah well that fixes it. Still curious what's up with sh – Zook Oct 6 '14 at 17:01
2

The problem seems to come from the builtin echo in dash (which is sh in Ubuntu by default), which seems to process its \ arguments differently from other implementations (/bin/echo and the builtin echo in Bash):

$ sh -c "echo '\\n'" 


$ sh -c "/bin/echo '\\n'"
\n
$ bash -c "echo '\\n'"
\n

This is not surprising, as using \ arguments in echo is non-standard:

http://pubs.opengroup.org/onlinepubs/009695399/utilities/echo.html

If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined.

You should use printf instead of echo, like this:

printf '$template GRAYLOGRFC5424,"<%%pri%%>%%protocol-version%% %%timestamp:::date-rfc3339%% %%HOSTNAME%% %%app-name%% %%procid%% %%msg%% \\n"\n' | sudo tee -a rsyslog.conf

As a added bonus, using sudo tee to write to files as root instead of sudo sh -c + shell redirections makes the command cleaner, since the string is parsed only once (as an argument to printf) instead of twice (first as an argument to sh -c and then as an argument to echo).

5
  • It already works, I'm looking for explanations. Why is that the right tool for the job? – Zook Oct 6 '14 at 17:03
  • Sorry, I misread. I'll edit my answer. – fkraiem Oct 6 '14 at 17:04
  • Using \n and friends with echo is non-standard? What reference do you have for such a statement? – muru Oct 6 '14 at 17:21
  • @muru I don't very much like your tone but... pubs.opengroup.org/onlinepubs/009695399/utilities/echo.html "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." – fkraiem Oct 6 '14 at 17:29
  • The source is very easily obtainable, for anyone who honestly wants it (as opposed to arguing for the sake of arguing). – fkraiem Oct 6 '14 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.