0

I am using \0n escape sequence with echo -e and printf where n is the octal value of the ASCII character to be printed. When i used the statement echo -e "\0101" the shell is printing character A but when i use printf "\0101" the shell is printing 1 which is the Least significant bit of the octal number i provided but if i remove 0 in the starting and use the command as printf "\101" it is correctly printing A as expected. so my doubt is why there is such a difference for this particular escape sequence, i tried for many other escape sequences but they gave same results with both echo and printf.I am using Ubuntu and currently working on bash.

4

From man echo1:

\0NNN byte with octal value NNN (1 to 3 digits)

From man printf1:

\NNN byte with octal value NNN (1 to 3 digits)

The two commands are not accepting the same format for octal sequences.

You can easily check that their actual output is quite different:

$ echo -en "\0101" | od -A n -t o1
 101

echo is actually printing the intended single character A.

$ printf "\0101" | od -A n -t o1
 010 061

printf, on the other hand, is seeing \010 as a character escape sequence and the subsequent 1 as a literal character, which is just copied to the output.
It is thus printing a <backspace> (which has no visible effect, being the first character of the string), whose octal representation is 010, followed by the non-interpreted 1.


1 To be precise, the commands you are running are most likely the Bash builtin ones, not those described by man (likely from coreutils). But both help echo and help printf confirm the man's syntax or directly refer to it.

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.