problem escaping newline in ksh

Hi,

I did the below.

$ print "\\n"

$

I am curious, why does \\n give two new lines? I would have thought that the first \ would escape the second \, and so we'd get \n printed. But we didn't.

Any ideas?

Thanks.

To get "\n" printed you need to add another \

print "\\\n"

Yes, you are right.

But why does "\\n" not print \n?

Any update, anyone?

OK,
print "\\n"

The shell peeks inside double quoted strings and processes stuff like variables and command substitution. During this inside peek, a backslash may be treated specially if it is followed one of these 4 characters: $`\" In other words, inside double quotes a backslash is used only to turn off the few characters that otherwise would be treated specially. So in the line,
somecommand "\n"
the shell treats the backslash as just a literal character since it is not followed by a character to interact with. So the command called "somecommand" is run with a single argument of just \n. Now in the case of a line like:
somecommand "\\n"
the first backslash interacts with the second backslash and prevents it from being special. It was destined to not be special anyway since it was not followed by one of the 4 characters it can interact with. But it is fine to explicitly make it non-special with an extra backslash. I usually do this to make the code more obvious.

So in either case, a command is being run with an argument of \n, but now we need to ask what the command will do with that argument. The print command, by default, processes some backslash combos as well. And yes, \n is one. You could use "print -r" or "print -R" to inhibit this.

That is a great reply. echo in tcsh gives very different results, so that was really confusing me!

So to clarify, for

print "\n"

...the shell simply interprets this as literally \n, and sends this to print. For print, a literal \n means newline, so it prints a newline. Yes?

For

print "\\n", 

the shell treats the first \ as special, because it is followed by a \. The shell takes this to mean that treat the second \ as non-special (which it already is). So the shell once again sends \n to print, and once again we get a newline. Yes?

For

print "\\\n"

the shell sees the first \ followed by a \, so the first \ is special. The second \ is not special, as it was escaped. The third \ is also not special, as it is followed by a n. So, the shell sends \\n as argument to print. Now print sees \\n as meaning do not treat \n as a newline, and so it prints \n onto the screen. Yes?

(Also, you said the shell only considers \ to be special if it is followed by \ , $ , " or `. So to shell \n does not mean a newline?)

Thanks.

Yes, your understanding is correct.

The only thing is that "print" is a built-in command to the shell. So what print does is really done by a part of the shell.

Thanks for the clarification :slight_smile: