Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

macos - Prevent "echo" from interpreting backslash escapes

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
part2" >> file

I would like to look like this in the file

$ cat file
old
part1
part2

but it looks like

$ cat file
old
part1
part2
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 echo1.

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
' 'part1
part2' >> file

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

part1
part2

being appended to file.


1 For an exhaustive overview of various behaviours for echo and printf, see echo(1) and printf(1) on in-ulm.de.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...