1

I want to clarify that I am not talking about how to escape characters on the shell level of interpretation.

As far as I can tell, only two character need to be escaped: % and \

To print a literal %, you must escape it with a preceding %:

printf '%%'

To print a literal \ you must escape it with a preceding \:

printf '\\'

Are there any other instances where I would need to escape a character for it to be interpreted literally?

  • looks like \' \" \? .......... a good search engine for this kind of stuff is symbolhound.com – jsotola Jan 16 at 4:32
  • I don't want to be (too) rude, but this is really a RTFM question. – glenn jackman Jan 16 at 16:40
  • Did my answer help? – Sparhawk Feb 10 at 20:58
0

From the manual:

$ man printf
...
   printf FORMAT [ARGUMENT]...
...
   FORMAT controls the output as in C printf.  Interpreted sequences are:

This lists several interpreted sequences. The following are those where the character itself needs to be escaped.

   \"     double quote
   \\     backslash
   %%     a single %

I tested these three in bash, and they behaved as expected. As per man bash, this implementation of printf uses the "standard printf(1) format specifications" as above, in addition to a few more that aren't relevant here.


However, other shells such as zsh implement printf slightly differently. Here, the double quote shouldn't be escaped.

$ printf '"'
"   
$ printf '\"'
\"
  • Yeah, same behavior here on dash and bash. For what it's worth, the dash manual makes no mention of needing the to escape ", but maybe I'm not reading in between the lines – Harold Fischer Jan 16 at 4:53
  • @HaroldFischer Presumably dash just inherits printf(1) too? I found the zsh manual a bit more opaque, so I didn't quote it here. – Sparhawk Jan 16 at 4:59
  • (edited) backslash-dquote is only needed if the format string is in dquotes, which is usually a bad idea, as then you also need to backslash backquote and (most) dollarsign, and may need to quadruple backslash if followed by a printf special. printf is builtin in bash and dash, but like all nonspecial builtins in a POSIX shell must also be present as an 'external' program. – dave_thompson_085 Jan 16 at 5:09
  • @dave_thompson_085, the question does say I want to clarify that I am not talking about how to escape characters on the shell level of interpretation. – Sparhawk Jan 16 at 5:10

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.