Prevent “echo” from interpreting backslash escapes

爷,独闯天下 提交于 2019-12-29 07:15:09

问题


I'd like to echo something to a file that contains new line escape sequences, however I would like them to remain escaped. I'm looking for basically the opposite to this question.

echo "part1\npart2" >> file

I would like to look like this in the file

$ cat file
old
part1\npart2

but it looks like

$ cat file
old
part1
part2

回答1:


This is a good example of why POSIX recommends using printf instead of echo (see here, under "application usage"): you don't know what you get with echo.

You could get:

  • A shell builtin echo that does not interpret backslash escapes by default
    • Example: the Bash builtin echo has an -e option to enable backslash escape interpretation and checks the xpg_echo shell option
  • A shell builtin echo that interprets backslash escapes by default
    • Examples: zsh, dash
  • A standalone executable /bin/echo: probably depends on which one – GNU Coreutils echo understands the -e option, like the Bash builtin

The POSIX spec says this (emphasis mine):

The following operands shall be supported:
string
A string to be written to standard output. If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined.

So, for a portable solution, we can use printf:

printf '%s\n' 'part1\npart2' >> file

where the \n in the format string will always be interpreted, and the \n in the argument will never be interpreted, resulting in

part1\npart2

being appended to file.



来源:https://stackoverflow.com/questions/43528202/prevent-echo-from-interpreting-backslash-escapes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!